简体   繁体   English

JavaScript:基于原型创建对象而不使用new + Constructor

[英]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.

相关问题 JavaScript-使用原型的构造函数 - JavaScript - Constructor using Prototype 新的JavaScript原型更改了构造函数 - New JavaScript prototype changes constructor Javascript-在不使用Array.prototype.filter的情况下基于键值获取两个对象数组之间的差异 - Javascript - getting difference between two arrays of objects based on key value without using Array.prototype.filter 使用带有和不带有“ new”的构造函数创建对象 - Creating an object using a constructor with and without `new` 新对象构造函数中的Javascript新数组原型 - Javascript new array prototype in new object constructor Javascript 构造函数创建与先前创建的具有相同值的新对象 object - Javascript constructor creating new objects with same values as previously created object 在没有.prototype的情况下向构造函数添加新属性 - Adding new properties to constructor function without .prototype JavaScript:使用没有运算符'new'的构造函数 - JavaScript: using constructor without operator 'new' Javascript:继承原型而不重定义构造函数 - Javascript: Inherit form a prototype without redefining the constructor 在构造函数中初始化的 JavaScript Prototype 属性不会被分配的新原型覆盖 - JavaScript Prototype properties initialized in constructor does not overrides with new prototype assigned
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM