JavaScript扩展对象和原型 [英] JavaScript extend objects and prototypes

查看:134
本文介绍了JavaScript扩展对象和原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个框架来简化使用原型的面向对象编码。但我正在思考JavaScript中的继承。

I am creating a framework to simplify the oriented object coding with prototypes. But I am pondering with inheritance in JavaScript.

默认情况下,为了扩展一个对象,我们写道:

By default, to extend an object, we write :

var B = function() { /*...*/ } ;
B.prototype = new A() ;

A 构造函数需要参数吗?

But what about A constructor function requires a parameter ?

var A = function(args) {
    if (!args) throw "Arguments required." ;
} ;

或者 构造函数也可以在之前执行不需要的操作B 是实例化的。

Or maybe A constructor function could also perform unwanted things before B was instancied.

您建议更换默认的继承行为?
(我考虑将所有类的所有成员存储起来,以便在继承或混合时复制。)

What would you suggest to replace the default inheritance behaviour ? (I thought about storing all the members of all "classes" to copy while inheriting or mixins.)

推荐答案

如果你想在不调用构造函数的情况下从原型继承,你可以使用 Object.create()来做这样的事情:

If you want to inherit from a prototype without calling the constructor, you can use Object.create() to do something like this:

var B = function() { /*...*/ };

B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

在上面, Object.create(A.prototype)将返回一个新对象,其原型由 A.prototype 给出,并且它在不调用 A()。第二行是那里你可以在B的任何实例上查找构造函数属性,它将指向 B()

In the above, Object.create(A.prototype) will return a new object whose prototype is given by A.prototype, and it does this without calling A(). The second line is there so you can look up the constructor property on any instances of B, and it'll point back to B().

需要注意的一点是 Object.create()相对较新,因此您可能需要为旧浏览器提供polyfill。你可以在这里找到一个,以及更多信息:

One thing to note is that Object.create() is relatively new, so you might need a polyfill for older browsers. You can find one here, along with more info:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

这篇关于JavaScript扩展对象和原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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