but when I am trying for obj2.name
, I am getting error object is not a function.
Not exactly. You're getting that error when you call var obj2=new obj1("sonali");
- where obj1
is the first instance, not your constructor. Use
var obj2 = new obj("sonali");
console.log(obj2.name); // works as expected
For better readability, the convention is to capitalise the names of constructor functions, so function Obj(name){…}
and var obj = new Obj(…)
.
per my understanding obj1
is inheriting properties from obj
No, obj1
is an instance. It does have the .name
property on itself, it doesn't inherit it, it does own it. obj
is the constructor function that created the property as part of the instance initialisation.
obj1
does inherit properties from obj.prototype
- since you didn't create any custom ones, the only inherited property is obj1.constructor
.
So when I am inheriting obj2
from obj1
it should inherit name property also.
As stated above, that's not what's happening. obj1
is not a constructor function, you cannot call it with new
. I bet I'm confusing you now, but you can still inherit from the obj1
instance object though: by using Object.create
. Let's start with
function Obj(name) {
this.name = name;
}
var obj1 = new Obj("suman"); // or alternatively:
obj1 = Object.create(Obj.prototype); obj1.name = "suman";
console.log(obj1.name); // suman
Now we can create a new object, inheriting prototypically from the first object:
var obj2 = Object.create(obj1);
console.log(obj2.name); // suman - inherited!
console.log(obj2.hasOwnProperty("name")); // false - it's inherited!
But now we can give it an own name as well:
obj2.constructor("sonali"); // which executes the following:
obj2.name = "sonali"; // pretty equivalent
console.log(obj2.name); // sonali