Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Creating objects based on a prototype without using new + Constructor

Tags:

javascript

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?

like image 612
plodder Avatar asked Feb 09 '10 17:02

plodder


People also ask

Can we create object without constructor in JavaScript?

Show activity on this post. Yes.

How do you create an object with prototype?

Object. create() method is used to create a new object with the specified prototype object and properties. Object. create() method returns a new object with the specified prototype object and properties.

Can we create an object without prototype?

create(null) creates an empty object without a prototype ( [[Prototype]] is null ): So, there is no inherited getter/setter for __proto__ .

How do you create an object in JavaScript that has no prototype?

The solution is to create an object without a prototype: var dict = Object. create(null);


1 Answers

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:

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();
  };
}
like image 103
Christian C. Salvadó Avatar answered Sep 21 '22 16:09

Christian C. Salvadó