admin管理员组文章数量:1289879
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
Am I missing something?
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
Am I missing something?
Share Improve this question asked Feb 9, 2010 at 17:16 plodderplodder 2,30618 silver badges19 bronze badges1 Answer
Reset to default 12You 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:
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.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.
For now you can mimic the behavior of that method by this, as proposed by Douglas Crockford:
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
本文标签: JavaScript Creating objects based on a prototype without using newConstructorStack Overflow
版权声明:本文标题:JavaScript: Creating objects based on a prototype without using new + Constructor - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741411854a2377281.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论