DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> JavaScript基礎知識 >> Javascript call和apply區別及使用方法
Javascript call和apply區別及使用方法
編輯:JavaScript基礎知識     

一、方法的定義
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 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方法:
復制代碼 代碼如下:
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);

三、作用實例

3.1、類的繼承
復制代碼 代碼如下:
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(“設計蜂巢”,24,”男”);
test.alertName();//設計蜂巢
test.alertAge();//24
test.alertSex();//男

3.2、回調函數
復制代碼 代碼如下:
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, ‘設計蜂巢', 2);
album.get_owner(function (owner) {
alert(‘The album' + this.name + ‘ belongs to ‘ + owner);
});

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved