Javascript继承和应用

前端之家收集整理的这篇文章主要介绍了Javascript继承和应用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在研究 Javascript中的设计模式,发现 http://tcorral.github.com/Design-Patterns-in-Javascript/Template/withoutHook/index.html是一个很好的来源.

anyonne可以解释使用ParentClass.apply(this)的重要性

  1. var CaffeineBeverage = function(){
  2.  
  3. };
  4. var Coffee = function(){
  5. CaffeineBeverage.apply(this);
  6. };
  7. Coffee.prototype = new CaffeineBeverage();

PS:我试过评论CaffeineBeverage.apply(这个),但没有效果.这是jsfiddle http://jsfiddle.net/pramodpv/8XqW9/链接

解决方法

它只是将父构造函数应用于正在构造的对象.尝试将一些东西添加到CaffeineBeverage构造函数中,你会明白我的意思.
  1. var CaffeineBeverage = function(){
  2. this.tweakage = '123';
  3. };
  4.  
  5. var Coffee = function(){
  6. CaffeineBeverage.apply(this);
  7. };

不要这样做:Coffee.prototype = new CaffeineBeverage().改为:

  1. Coffee.prototype = Object.create(CaffeineBeverage.prototype);

有关它的更多信息,请参阅this article,它还为没有Object.create的旧浏览器提供填充程序.

测试出来:

  1. var drink = new Coffee();
  2. console.log(drink.tweakage); // 123

猜你在找的JavaScript相关文章