[英]JavaScript: Creating objects based on a prototype without using new + Constructor
is this possible? 这可能吗?
My thinking: Prototypes are essentially attributes of the Constructor function (whether native Constructor such as Function, String or Object, or your own custom Constructor) and only the 'new' keyword is able to leverage the Constructor and its prototype for object creation 我的想法:原型本质上是构造函数的属性(无论是本机构造函数,如Function,String或Object,还是您自己的自定义构造函数),只有'new'关键字能够利用构造函数及其原型来创建对象
Am I missing something? 我错过了什么吗?
You are right, but now in the ECMAScript 5th Edition, the Object.create
method is able to create object instances using another objects as a prototype: 你是对的,但现在在ECMAScript第5版中,
Object.create
方法能够使用另一个对象作为原型创建对象实例:
var proto = {foo: 1};
var obj = Object.create(proto);
In the above example, obj
will be created and it will contain a reference to proto
in the [[Prototype]]
internal property, and: 在上面的例子中,将创建
obj
,它将在[[Prototype]]
内部属性中包含对proto
的引用,并且:
obj.foo; // 1
obj.hasOwnProperty('foo'); // false
This method is from the new specification approved on December 2009, as far I've seen now is available on the Mozilla JavaScript 1.9.3 implementation. 这个方法来自2009年12月批准的新规范,到目前为止我已经看到Mozilla JavaScript 1.9.3实现了。
For now you can mimic the behavior of that method by this, as proposed by Douglas Crockford : 现在你可以像Douglas Crockford所建议的那样模仿那个方法的行为:
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.