I know this Question might have been asked already in different ways on stackoverflow but still
I just need to clarify my doubt
There is one prop in Object Constructor namely prototype.
And there is Object.prototype Object.
So when i am writing something as Object.prototype=object2
Am I setting the prototype property on the Object Constructor or Object.prototype Object is getting the values from object2 by reference.
1 Answer
You are setting the prototype of Object to object2, by reference.
var dogProto = {
bark: 'woof'
};
// Define a Dog class
var Dog = (function() {});
// Set its prototype to that which is contained in proto
Dog.prototype = dogProto;
// Make a Dog
var fido = new Dog;
// What's the bark property of fido?
console.log(fido.bark); // outputs: woof
// Modify the original dogProto object
dogProto.bark = dogProto.bark.toUpperCase();
// What's the bark property of fido now?
console.log(fido.bark); // outputs: WOOF
2 Comments
steveluscher
It is written in Javascript. Copy and paste the code into this to watch it run: repl.it/languages/JavaScript
HMR
Setting prototype of Dog in this way will have
fido.constructor point to Object() instead of Dog Dog.prototype.bark="woof" would be saver if you want to use constructor at some point. Like Dog.prototype.haveAKid=function(){return new this.constructor();}
var anObject=new Object();anObject.constructor === Object;//true var anotherObject=new anObject.constructor()