call方法可改變上下文this指針,類似的方法還有apply,只是調(diào)用方式上有些不同
call 方法
調(diào)用一個(gè)對(duì)象的一個(gè)方法,以另一個(gè)對(duì)象替換當(dāng)前對(duì)象。
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
參數(shù)
thisObj
可選項(xiàng)。將被用作當(dāng)前對(duì)象的對(duì)象。
arg1, arg2, , argN
可選項(xiàng)。將被傳遞方法參數(shù)序列。
說明
call 方法可以用來代替另一個(gè)對(duì)象調(diào)用一個(gè)方法。call 方法可將一個(gè)函數(shù)的對(duì)象上下文從初始的上下文改變?yōu)橛?thisObj 指定的新對(duì)象。
如果沒有提供 thisObj 參數(shù),那么 Global 對(duì)象被用作 thisObj。
function product(name, value){
? ?this.name = name;
? ?if(value > 1000)
? ? ? this.value = 999;
? ?else
? ? ? this.value = value;
}
function prod_dept(name, value, dept){
? ?this.dept = dept;
? ?product.call(this, name, value);
}
prod_dept.prototype = new product();
// since 5 is less than 100 value is set
cheese = new prod_dept("feta", 5, "food");
// since 5000 is above 1000, value will be 999
car = new prod_dept("honda", 5000, "auto");
call 方法
調(diào)用一個(gè)對(duì)象的一個(gè)方法,以另一個(gè)對(duì)象替換當(dāng)前對(duì)象。
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
參數(shù)
thisObj
可選項(xiàng)。將被用作當(dāng)前對(duì)象的對(duì)象。
arg1, arg2, , argN
可選項(xiàng)。將被傳遞方法參數(shù)序列。
說明
call 方法可以用來代替另一個(gè)對(duì)象調(diào)用一個(gè)方法。call 方法可將一個(gè)函數(shù)的對(duì)象上下文從初始的上下文改變?yōu)橛?thisObj 指定的新對(duì)象。
如果沒有提供 thisObj 參數(shù),那么 Global 對(duì)象被用作 thisObj。
function product(name, value){
? ?this.name = name;
? ?if(value > 1000)
? ? ? this.value = 999;
? ?else
? ? ? this.value = value;
}
function prod_dept(name, value, dept){
? ?this.dept = dept;
? ?product.call(this, name, value);
}
prod_dept.prototype = new product();
// since 5 is less than 100 value is set
cheese = new prod_dept("feta", 5, "food");
// since 5000 is above 1000, value will be 999
car = new prod_dept("honda", 5000, "auto");