var a = function () {};
a.prototype.test = function () {
alert("hello");
}
works fine but in following code
var b = new Object();
b.prototype.test = function () {
alert("hello");
}
i am getting this error TypeError: Cannot set property ‘test’ of undefined and i am unable to get it.
As per my understanding b has inherited prototype object from Object. So we should be able to add a new property in following manner say b.prototype.x = 1 .
But Object.prototype.x = 1 works .
typeof Object and a gives function but that of b is object
I am not getting why b.prototype.x = 1 doesnt work
Thanks.
Objectis a function, which has aprototypeproperty.new Object()creates an object, which does not have aprototypeproperty.If you want to set the prototype of an object, you might mean setting the prototype of the object’s constructor.
To clarify some of the prototype/constructor nonsense:
A function has a
prototype, which is an object. It specifies properties to add to an instance of that function.An object has a
constructor, which is a function. It specifies the function that was used to create the object.Note that a function is an object, so it also has a
constructor, which isFunction.