一、方法的定義
call方法:
語法:fun.call(thisArg[, arg1[, arg2[, ...]]])
定義:調用一個對象的一個方法,以另一個對象替換當前對象。
說明:
call 方法可以用來代替另一個對象調用一個方法。call 方法可將一個函數的對象上下文從初始的上下文改變為由 thisArg 指定的新對象。
如果沒有提供 thisArg參數,那么 Global 對象被用作 thisArg。
apply方法:
語法:fun.apply(thisArg[, argsArray])
定義:應用某一對象的一個方法,用另一個對象替換當前對象。
說明:
如果 argArray 不是一個有效的數組或者不是 arguments 對象,那么將導致一個 TypeError。
如果沒有提供 argArray 和 thisArg 任何一個參數,那么 Global 對象將被用作 thisArg, 并且無法被傳遞任何參數。
二、兩者區別
兩個方法基本區別在于傳參不同
2.1、call方法:
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
Food.prototype = new Product();
function Toy(name, price) {
Product.call(this, name, price);
this.category = 'toy';
}
Toy.prototype = new Product();
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
function Food(name, price) {
Product.apply(this, arguments);
this.category = 'food';
}
Food.prototype = new Product();
function Toy(name, price) {
Product.apply(this, arguments);
this.category = 'toy';
}
Toy.prototype = new Product();
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
3.1、類的繼承
function webDever(name,age,sex){
Person.call(this,name,age);
this.sex=sex;
this.alertSex = function(){
alert(this.sex);
}
}
var test= new webDever(“設計蜂巢”,24,”男”);
test.alertName();//設計蜂巢
test.alertAge();//24
test.alertSex();//男
|
新聞熱點
疑難解答