Search code examples
prototypejsprototype-programmingjavascript

creating an instance of another object in javascript


I want to know whether this sentence is correct?

You can do:

var a = new A();

if and only if A is instanceof Function.

Simply you can create an instance of function and you know a function is an object. Why can't we create an instance of other user-defined objects? Like this:

var b={};
var c = new b();  //error

EDIT: How can I change b so that I can create an instance of that?


Solution

  • You can actually use Object.create() to have some sugar around ECMAscript's prototypal nature. Like

    var b = { };
    var c = Object.create( b );
    

    Now, c will have b on its prototype chain. ECMAscript or more precisely, prototypal inheritance doesn't work exactly the same way as a "classical inheritance". By calling new when invoking a function, you actually receiving a newly created object aswell. You can modify and access that object via the this value within that such called constructor function.

    However, you didn't inherit anything so far. You would need to create and fill the .prototype - object for your constructor function before you create instances of it. This pattern annoyed lots of people, so ES5 brought as a more convinient way to directly inherit from other objects using Object.create().