Reputation: 1940
I was experimenting with inheritance and creating objects and somehow this confused me.
a = function (){console.log("test"); return "hello"};
b = new a();
//console output
test VM719:2
a {}
What does this mean ? Does it mean b contains a ? if so then if I do this
console.log(b.a);
//console output
undefined
undefined
Why this is so ? Secondly if I do this
b.__proto__
//console output
Object {}
a.prototype.test ="hello";
b.__proto__
//console output
Object {test: "hello"}
This is fine as new causes b s prototype to point to a.
console.log(b);
//console output
a {test: "hello"}
What does this output mean ? When i log b.test it gives "hello" but when i log b.a it gives "undefined" .So what is the significance of a in the output console ?
Upvotes: 2
Views: 62
Reputation: 94121
a {}
means is an object instance of a
, because you used new
you create an instance. The properties of that object are those of the prototype
that are shared with all other instances, in your case test
. Instance properties must be created in the constructor, like so:
function A() {
this.prop = 'hello';
}
A.prototype.test = function(){}; // shared with other instances
var b = new A();
b.prop; //=> 'hello' // unique to this instance
Upvotes: 2
Reputation: 534
If a constructor function returns nothing, null, or any atomic / non-object value then said value is ignored and the newly created object reference is given back to the caller. So u see the constructor of your object in console...
Upvotes: 6