我一直在研究Javascript中的设计模式,并发现http://tcorral.github.com/Design-Patterns-in-Javascript/Template/withoutHook/index.html是一个很好的来源.
anyonne可以解释使用ParentClass.apply(this)的重要性
var CaffeineBeverage = function(){
};
var Coffee = function(){
CaffeineBeverage.apply(this);
};
Coffee.prototype = new CaffeineBeverage();
Run Code Online (Sandbox Code Playgroud)
PS:我试过评论CaffeineBeverage.apply(这个),但没有效果.这是jsfiddle http://jsfiddle.net/pramodpv/8XqW9/的链接
Dag*_*bit 13
它只是将父构造函数应用于正在构造的对象.尝试添加一些东西到CaffeineBeverage构造函数,你会看到我的意思.
var CaffeineBeverage = function(){
this.tweakage = '123';
};
var Coffee = function(){
CaffeineBeverage.apply(this);
};
Run Code Online (Sandbox Code Playgroud)
不要这样做:Coffee.prototype = new CaffeineBeverage().改为:
Coffee.prototype = Object.create(CaffeineBeverage.prototype);
Run Code Online (Sandbox Code Playgroud)
有关这方面的更多信息,请参阅此文章,该文章还提供了旧版浏览器的垫片,这些垫片没有Object.create.
测试出来:
var drink = new Coffee();
console.log(drink.tweakage); // 123
Run Code Online (Sandbox Code Playgroud)
不要看那个例子,让我们充实自己:
var Room = function()
{
this.doors = 1;
};
Run Code Online (Sandbox Code Playgroud)
很像call,apply将执行该功能,但允许您指定是什么this.在上面的例子中,我指定this.doors = 1,doors当我们创建我们的实例时,它成为一个成员Room.
现在,如果我这样做:
var ComputerRoom = function()
{
Room.apply(this);
// I can now access the this.doors member:
this.doors = this.doors + 1;
};
Run Code Online (Sandbox Code Playgroud)
我实际上是说this在Room构造函数的上下文中,实际上是实例ComputerRoom,这就是我将它传递给apply命令的原因:Room.apply(this).