您的位置:首页 > 移动开发

JS 中的call 和 apply ,以及实现继承的一些研究

2014-07-31 10:21 609 查看
好久不写东西,才知道自己早就丢失了写作这项技能。

最近得空,有时间研究了一些困扰自己很久的东西,这里就先从js开始,在这里做一下记录。让自己浮躁的心,得到一些沉淀。

这里要谈的是js 的call() 和 apply() 方法。这两都是js 的prototype 方法,由于今天的重点不在这里,所以就不做过多的停留,直接进入正题。

在写这些demo之前,还是习惯性的到js官网去看了一眼。它对于call()的描述是这样的。

The
call()
method calls a function with a given
this
value
and arguments provided individually.

Note: While the syntax of this function is almost identical to that of
apply()
,
the fundamental difference is that
call()
accepts an argument
list, while
apply()
accepts a single array of arguments.
来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
大概就是说 call() 是用来调用某个方法,通过给定的this(就我所知,js的this 对象是跟所调用者绑定的,这里给了我们另外一种可能) ,同时这里所提到的单个的参数,也说明了他和apply()的不同之处:apply 所传的参数是数组

继续引用官网的demo

function Product(name, price) {

this.name = name;

this.price = price;

return this;

}

function Food(name, price) {

Product.call(this, name, price);

this.category = 'food';

}

Food.prototype = Object.create(Product.prototype);

function Toy(name, price) {

Product.call(this, name, price);

this.category = 'toy';

}

Toy.prototype = Object.create(Product.prototype);

var cheese = new Food('feta', 5);

var fun = new Toy('robot', 40);

console.log(cheese.category);

上面的代码利用这一特性实现了js的继承, food和 toy 继承了 product 的name 和 price 这两个属性。

下面的代码则是完成了调用,为function 执行过程中指定了 this 对象。

var animals = [

{species: 'Lion', name: 'King'},

{species: 'Whale', name: 'Fail'}

];

for (var i = 0; i < animals.length; i++) {

(function (i) {

this.print = function () {

console.log('#' + i + ' ' + this.species

+ ': ' + this.name);

}

this.print();

}).call(animals[i], i);

}

好吧,由于本人知识能力限制,文章也就到此为止,文中的不足甚至错误,如果能得到读者的不吝赐教,不胜感激 。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: