Javascript call和apply区别及使用方法 |
一、方法的定义 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) { function Toy(name, price) { var cheese = new Food(feta, 5); 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) { function Toy(name, price) { var cheese = new Food(feta, 5); 三、作用实例 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){ var test= new webDever(“设计蜂巢”,24,”男”); 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); }); |