javascript中的call和apply方法介紹

來源:互聯網
上載者:User

標籤:

/*建構函式模式*/
function Person(name, age, job) {
    this.name = name;
    this.age = age;
    this.job = job;
    sayName = function() {
        alert(this.name);
    };
}
var personThis=new Person("thisLff", 24, "doctor");//①當建構函式來使用
//建構函式對象都有一個constructor(建構函式)屬性,該屬性指向Person
alert(personThis.constructor==Person);//true
/*②作為普通函數調用*/
Person("11",11,"11");//添加到windows
windows.sayName();//"11"
/*③在另一個對象的範圍中調用*/
var o=new Object();
Person.call(o,"22",22,"22");//第一個參數是o,說明應該賦予Person中的 this 關鍵字值是o
o.sayName();//"22"

使用call()和apply()方法主要是為了修改函數運行時的this指標call() 方法

call() 方法是與經典的對象冒充方法最相似的方法。它的第一個參數用作 this 的對象。其他參數都直接傳遞給函數自身。例如:

function sayColor(sPrefix,sSuffix) {    alert(sPrefix + this.color + sSuffix);};var obj = new Object();obj.color = "blue";sayColor.call(obj, "The color is ", "a very nice color indeed.");

在這個例子中,函數 sayColor() 在對象外定義,即使它不屬於任何對象,也可以引用關鍵字 this。對象 obj 的 color 屬性等於 blue。調用 call() 方法時,第一個參數是 obj,說明應該賦予 sayColor() 函數中的 this 關鍵字值是 obj。第二個和第三個參數是字串。它們與 sayColor() 函數中的參數 sPrefix 和 sSuffix 匹配,最後產生的訊息 "The color is blue, a very nice color indeed." 將被顯示出來。

apply() 方法

apply() 方法有兩個參數,用作 this 的對象和要傳遞給函數的參數的數組。例如:

function sayColor(sPrefix,sSuffix) {    alert(sPrefix + this.color + sSuffix);};var obj = new Object();obj.color = "blue";sayColor.apply(obj, new Array("The color is ", "a very nice color indeed."));

這個例子與前面的例子相同,只是現在調用的是 apply() 方法。調用 apply() 方法時,第一個參數仍是 obj,說明應該賦予 sayColor() 函數中的 this 關鍵字值是 obj。第二個參數是由兩個字串構成的數組,與 sayColor() 函數中的參數 sPrefix 和 sSuffix 匹配,最後產生的訊息仍是 "The color is blue, a very nice color indeed.",將被顯示出來。

javascript中的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.