Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 742
Dariush Jafari Avatar asked Jul 29 '26 23:07

Dariush Jafari


1 Answers

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().

like image 163
jAndy Avatar answered Aug 01 '26 12:08

jAndy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!