您好,欢迎访问一九零五行业门户网

Javascript call和apply区别及使用方法

一、方法的定义
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); });
更多javascript call和apply区别及使用方法。
其它类似信息

推荐信息