cynx
cynx

Reputation: 387

JavaScript Prototype method not found on object

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();

Upvotes: 2

Views: 2077

Answers (1)

Felix Kling
Felix Kling

Reputation: 816302

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);
  }
});

Upvotes: 6

Related Questions