欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Javascript call和apply區(qū)別及使用方法

 更新時(shí)間:2013年11月14日 16:43:18   作者:  
JavaScript中通過call或者apply用來代替另一個(gè)對象調(diào)用一個(gè)方法,將一個(gè)函數(shù)的對象上下文從初始的上下文改變?yōu)橛?thisObj 指定的新對象

一、方法的定義
call方法:
語法:fun.call(thisArg[, arg1[, arg2[, ...]]])
定義:調(diào)用一個(gè)對象的一個(gè)方法,以另一個(gè)對象替換當(dāng)前對象。
說明:
call 方法可以用來代替另一個(gè)對象調(diào)用一個(gè)方法。call 方法可將一個(gè)函數(shù)的對象上下文從初始的上下文改變?yōu)橛?thisArg 指定的新對象。
如果沒有提供 thisArg參數(shù),那么 Global 對象被用作 thisArg。

apply方法:
語法:fun.apply(thisArg[, argsArray])
定義:應(yīng)用某一對象的一個(gè)方法,用另一個(gè)對象替換當(dāng)前對象。
說明:
如果 argArray 不是一個(gè)有效的數(shù)組或者不是 arguments 對象,那么將導(dǎo)致一個(gè) TypeError。
如果沒有提供 argArray 和 thisArg 任何一個(gè)參數(shù),那么 Global 對象將被用作 thisArg, 并且無法被傳遞任何參數(shù)。

二、兩者區(qū)別
兩個(gè)方法基本區(qū)別在于傳參不同
2.1、call方法:

復(fù)制代碼 代碼如下:

function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0)
throw RangeError('Cannot create product "' + name + '" with a negative price');
return this;
}

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);


2.2、apply方法:
復(fù)制代碼 代碼如下:

function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0)
throw RangeError('Cannot create product "' + name + '" with a negative price');
return this;
}

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);


三、作用實(shí)例

3.1、類的繼承

復(fù)制代碼 代碼如下:

function Person(name,age){
this.name = name;
this.age=age;
this.alertName = function(){
alert(this.name);
}
this.alertAge = function(){
alert(this.age);
}
}

function webDever(name,age,sex){
Person.call(this,name,age);
this.sex=sex;
this.alertSex = function(){
alert(this.sex);
}
}

var test= new webDever(“設(shè)計(jì)蜂巢”,24,”男”);
test.alertName();//設(shè)計(jì)蜂巢
test.alertAge();//24
test.alertSex();//男


3.2、回調(diào)函數(shù)
復(fù)制代碼 代碼如下:

function Album(id, title, owner_id) {
this.id = id;
this.name = title;
this.owner_id = owner_id;
};
Album.prototype.get_owner = function (callback) {
var self = this;
$.get(‘/owners/' + this.owner_id, function (data) {
callback && callback.call(self, data.name);
});
};
var album = new Album(1, ‘設(shè)計(jì)蜂巢', 2);
album.get_owner(function (owner) {
alert(‘The album' + this.name + ‘ belongs to ‘ + owner);
});

相關(guān)文章

最新評論