2

From what I have read, if a property or method is not found on the object, its searched on prototype of the object. In below example, I have created an object. Then assigned prototype of that object to a object literal. I am now able to access the method of object's prototype. But not able to access same on object. Why so?

var functionMaster = Object.create(null); 
//assign proto to below object literal
functionMaster.prototype = {
 printVal: function() {
 console.log('Hello test');
 },
 printNo: function(num) {
 console.log(num);
 }
}
//Works as expected
functionMaster.prototype.printVal();
//Doesnt find PrintVal() method
functionMaster.printVal();

Felix Kling
820k181 gold badges1.1k silver badges1.2k bronze badges
asked Feb 11, 2016 at 6:29
2
  • you need to use constructor functions to create inheritable prototypes. Commented Feb 11, 2016 at 6:34
  • prototype properties are only used by new with constructor functions. With Object.create(), the argument is your chance specify a prototype (currently null). Commented Feb 11, 2016 at 6:36

1 Answer 1

6

Then assigned prototype of that object to a object literal.

No you haven't. The prototype property only has a special meaning on (constructor) function objects:

function Constr() {}
Constr.prototype.foo = 42;
var instance = new Constr();
console.log(instance.foo); // 42
console.log(Object.getPrototypeOf(instance) === Constr.prototype); // true

In your case, assigning a prototype property to an object, it is just an ordinary property with no special meaning. You can verify this by running Object.getPrototypeOf(functionMaster). It will return null.

But not able to access same on object. Why so?

The object doesn't have a prototype at all since you explicitly set it to null. You either want

var functionMaster = Object.create({
 printVal: function() {
 console.log('Hello test');
 },
 printNo: function(num) {
 console.log(num);
 }
}); 

or

Object.setPrototypeOf(functionMaster, {
 printVal: function() {
 console.log('Hello test');
 },
 printNo: function(num) {
 console.log(num);
 }
});
answered Feb 11, 2016 at 6:35
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Felix. Very well explained. Also, I am not able to use functionMaster.prototype.printVal(); even when object has an prototype created by Object.setPrototypeOf because prototype property will work only with function objects (Constructors)?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.