2

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 ?

1
  • 2
    it is mean that b is type of a Commented Dec 25, 2013 at 7:58

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for actually explaining what happens with the return value.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.