關於call 和 apply

來源:互聯網
上載者:User

標籤:

權威指南上的說法是:可以將call 和apply看做是某個對象的方法,通過調用方法的形式

間接調用函數;需要重點說明是 :通過call和apply 調用的 函數:具體用法---》如下:

1.先說call的用法,call可以接收兩個參數,也可能不是兩個;第一個參數是要調用函數的

母對象,在函數體內通過this來獲得對它的引用;

function a(){
console.log(this); // 輸出函數a中的this對象
}

function b(){} // 定義函數b
var obj = {name:‘onepixel‘}; //定義對象obj

//調用
a();//this代表window對象;
a.call;//本身是一個函數方法//window
console.log(a.call); //function call() { [native code] };
a.call(null); //window 傳入null,函數中的this,指向window
a.call(undefined);//window 傳入undefined,函數中的this,指向window
a.call(1); //Number 傳入數值型,this指向對應的封裝類型,Number
a.call(‘‘); //String 傳入字串,this指向string 類型
a.call(true); //Boolean 傳入布爾類型,this指向Boolean類型
a.call(b);//function b(){}
a.call(obj); //Object 指向obj;
//call的用法;

可以看到call()中第一個參數出入什麼樣的參數,this 就指向對應的封裝類型;

不傳參,或者參數為null,undefined 時,this指向window;

具體用法:

//call的用法;
var m = {
  name:‘onepixel‘,
    say:function(){
    console.log(‘hi,i am function m!‘);
    },
  }

  function n(name){
    console.log(‘post params:‘+name);
    console.log(‘i am ‘+this.name);
    this.say;
  }
n.call(m,‘test‘);//post params:test
// i am onepixel
//I‘m function a! 不知道為什麼沒有調用;

也就是說n可以通過call來調用M 中的方法; 
//關於appply
//apply和call的唯一區別是第二個參數的傳遞方式不同,
//apply的第二個參數必須是一個數組,而call允許傳遞一個參數列表
//值得你注意的是,雖然apply接收的是一個參數數組,但在傳遞給調用函數時,
//卻是以參數列表的形式傳遞

function f(x,y,z){
console.log(x,y,z)
}
f.apply(undefined,[1,2,3]);//1,2,3

//第一個參數傳null或undedined指向window
重點://js中麼有繼承的概念,call和apply卻可以實現;

function Animal(name,weight){
    this.name = name;
    this.weight = weight;
  }
function Cat(){
    Animal.call(this,‘cat‘,‘50‘);
    //Animal.apply(this,[‘cat‘,‘50‘]);
    this.say = function(){
    console.log(‘i am ‘+this.name+‘myweight‘+this.weight)
    }

  }

var cat = new Cat();
cat.say();

這段代碼自己理解一下。。。。

 

關於call 和 apply

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.