Javascript继承&应用 [英] Javascript inheritance & Apply

查看:49
本文介绍了Javascript继承&应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究Javascript中的设计模式,发现 http://tcorral.github.com/Design-Patterns-in-Javascript/Template/withoutHook/index.html 是一个很好的来源。

I have been looking into design patterns in Javascript and found http://tcorral.github.com/Design-Patterns-in-Javascript/Template/withoutHook/index.html to be a great source.

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

Can anyonne explain the significance of using ParentClass.apply(this)

var CaffeineBeverage = function(){

};
var Coffee = function(){
    CaffeineBeverage.apply(this);
};
Coffee.prototype = new CaffeineBeverage();

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

PS: I tried commenting the CaffeineBeverage.apply(this), but no effect was there. Here is a link to jsfiddle http://jsfiddle.net/pramodpv/8XqW9/

推荐答案

它只是将父构造函数应用于正在构造的对象。尝试将一些东西添加到 CaffeineBeverage 构造函数中,你会看到我的意思。

It simply applies the parent constructor to the object being constructed. Try adding some stuff to the CaffeineBeverage constructor and you'll see what I mean.

var CaffeineBeverage = function(){
    this.tweakage = '123';
};

var Coffee = function(){
    CaffeineBeverage.apply(this);
};

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

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

有关详细信息,请参阅这篇文章,它还为旧浏览器提供了一个垫片,它没有 Object.create

For more information on that, see this article, which also provides a shim for older browsers, which don't have Object.create.

测试出来:

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

这篇关于Javascript继承&应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆