国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Javascript call和apply區別及使用方法

2019-11-20 21:41:57
字體:
來源:轉載
供稿:網友

一、方法的定義
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);
});

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 杂多县| 庆阳市| 吉木乃县| 开鲁县| 东方市| 闻喜县| 会东县| 通化市| 阿克苏市| 古浪县| 化德县| 凤台县| 汝南县| 东莞市| 巴里| 壤塘县| 孟州市| 东阿县| 莒南县| 孝义市| 孟村| 修武县| 永昌县| 黄山市| 札达县| 长兴县| 奉节县| 敖汉旗| 兴和县| 霍城县| 互助| 垫江县| 自治县| 中西区| 淮阳县| 灵石县| 石首市| 山阳县| 西华县| 玉林市| 台中县|