徹底理解了call()方法,apply()方法和bind()方法

來源:互聯網
上載者:User

標籤:必須   ons   個數   person   blog   win   function   變數   並且   

javascript中的每一個範圍中都有一個this對象,它代表的是調用函數的對象。在全域範圍中,this代表的是全域對象(在web瀏覽器中指的是window)。如果包含this的函數是一個對象的方法,this指向的就是這個對象。因此在上面例子中就不用直接寫對象的名字,而是使用this代替它,例如:

var human = {    name: ‘霍林林‘,    sayName: function(){        console.log(this.name);    }}human.sayName();

下面這個例子中,我們直接使用person.name,這種做法會增加方法與對象之間的耦合度(它們之間的依賴性變強了)。這樣寫是有問題的 ,如果我們的變數名修改了,我們必須同時修改方法中的變數名。幸運的是,JavaScript給我們提供瞭解決這個問題的方法。

var person = {        name: ‘霍林林‘,        sayName: function(){            console.log(person.name);        }    }    person.sayName();
1.改變this

this通常是被自動賦值的,但是我們可以改變this的指向。JavaScript給我們提供了 3 中 函數方法 來改變this的指向。

2.call()方法

這個方法的第一個參數表示this指向的對象,後面的所有參數都是函數的參數。例如:

function sayName(label) {    console.log(label+‘--->‘+this.name);}var name = ‘張三‘;var person1 = {    name: ‘李四‘};var person2 = {    name: ‘王二‘};sayName.call(window,‘global‘);      //‘global--->張三‘sayName.call(person1,‘person1‘);    //‘person1--->李四‘sayName.call(person2,‘person2‘);    //‘person2--->王二‘
3.apply()方法

這個方法和call方法的作用都是相同的,只不過在傳遞參數時候,call方法可以傳遞多個參數,而apply方法只能傳遞一個方法,並且要求是一個數組。

function sayName(label) {    console.log(label);    console.log(this.name);}var name = ‘張三‘;var person1 = {    name: ‘李四‘};var person2 = {    name: ‘王二‘};sayName.apply(window,[‘global‘]);   //‘global--->張三‘sayName.apply(person1,[‘person1‘]); //‘person1--->李四‘sayName.apply(person2,[‘person2‘]); //‘person2--->王二‘
4.bind()方法

bind()方法第一個參數是我們希望函數中this指向的對象,後面的參數是我們希望給函數的參數綁定的值。

var obj = {              name:‘小明‘              age:23            };function myName(age,gender){              console.log(this.name,age,gender);            }var newName = myName.bind(obj);
            newName();  //小明 undefined undefined                        var newName2 = myName.bind(obj,18);            newName2();  //小明 18 undefined                        var newName3 = myName.bind(obj,18,‘女‘);            newName3();  //小明 18 女                        var newName4 = myName.bind(obj);            newName4(18,‘女‘);  //小明 18 女

 

徹底理解了call()方法,apply()方法和bind()方法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.