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
refrence 1
refrence 2
refrence 3
getPrototypeOf() The Object. getPrototypeOf() method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object.
JavaScript has two types of objects: function object and non-function object. Conceptually, all objects have a prototype (NOT A PROTOTYPE PROPERTY).
Each and every JavaScript function will have a prototype property which is of the object type. You can define your own properties under prototype . When you will use the function as a constructor function, all the instances of it will inherit properties from the prototype object.
Note: The property of an object that points to its prototype is not called prototype . Its name is not standard, but in practice all browsers use __proto__ . The standard way to access an object's prototype is the Object. getPrototypeOf() method.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With