我一直在研究 Javascript 中的设计模式并发现http://tcorral.github.com/Design-Patterns-in-Javascript/Template/withoutHook/index.html http://tcorral.github.com/Design-Patterns-in-Javascript/Template/withoutHook/index.html成为一个伟大的来源。
谁能解释一下使用的意义父类.apply(this)
var CaffeineBeverage = function(){
};
var Coffee = function(){
CaffeineBeverage.apply(this);
};
Coffee.prototype = new CaffeineBeverage();
PS:我尝试评论 CaffeineBeverage.apply(this),但没有效果。这是 jsfiddle 的链接http://jsfiddle.net/pramodpv/8XqW9/ http://jsfiddle.net/pramodpv/8XqW9/
它只是将父构造函数应用于正在构造的对象。尝试添加一些东西到CaffeineBeverage
构造函数,你就会明白我的意思了。
var CaffeineBeverage = function(){
this.tweakage = '123';
};
var Coffee = function(){
CaffeineBeverage.apply(this);
};
不要这样做:Coffee.prototype = new CaffeineBeverage()
。改为这样做:
Coffee.prototype = Object.create(CaffeineBeverage.prototype);
有关详细信息,请参阅本文 http://javascript.crockford.com/prototypal.html,它还为较旧的浏览器提供了一个填充程序,这些浏览器没有Object.create
.
测试一下:
var drink = new Coffee();
console.log(drink.tweakage); // 123
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)