Well I am curios to learn about prototypes in javascript and found many articles however i am not able to understand why am i not able to use prototypes in Object literals in javascript. As we all know, everything is inherited from Object so in that case
function Dog() {
}
Dog.prototype = new Animal;
Dog.prototype.bark = function() {
console.log("Woof! My name is " + this.name);
};
If I am able to use prototype in the function why am i not able to use prototype in the object literals for instance the below example
var obj = {
firstname: 'foo',
lastname:'bar'
}
// this throws an error
obj.prototype.getMethod = function () {
console.log('this is a function');
}
I have gone through all this question but it really doesnt answer the reason why cant use prototype in the object literals in javascript. Below are some of the references
First of all, the .prototype
property belongs to function object. You cannot access it from a plain object instance. Basically the constructor-associated .prototype
property will be used when constructing the internal [[prototype]]
of an instance. Here you are having an instance, if you want to add the function to the prototype chain of it, then you have to modify it by
var obj = { firstname: 'foo', lastname:'bar' };
var pro = Object.getPrototypeOf(obj);
pro.getMethod = function () {
console.log('this is a function');
};
As @bergi pointed out, there is a risk of adding the getMethod
to all the instances if we follow the above approach. But in order to avoid that you could alternatively do,
var obj = { firstname: 'foo', lastname:'bar' };
Object.setPrototypeOf(obj, Object.create({getMethod : function(){
console.log("Hello");
}}));
console.log(obj.getMethod()); //"Hello"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.