Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of prototype in javascript

Tags:

I wrote short code of inheritance of reader from Person:

<script>

/* Class Person. */
function Person(name) {
    this.name = name;
}

Person.prototype.getName = function() {
    return this.name;
}

var reader = new Person('John Smith');
alert(reader.getName());

</script>

Alternatively I can delete the line of Person.prototype.getName = function() { return this.name; } and create it in the Person object. For example

<script>
/* Class Person. */
function Person(name) {
    this.name = name;
    this.getName = function() { return this.name;}
}

var reader = new Person('John Smith');
alert(reader.getName());

</script>

I got the same result when invoking getName() in both these cases. So how are they different?

like image 602
user1365697 Avatar asked Jul 18 '12 12:07

user1365697


People also ask

What is Proto and prototype in JavaScript?

The prototype property is set to function when it is declared. All the functions have a prototype property. proto property that is set to an object when it is created using a new keyword. All objects behavior newly created have proto properties.

Why is JavaScript prototype based?

JavaScript is a prototype-based language, meaning object properties and methods can be shared through generalized objects that have the ability to be cloned and extended.

What does __ proto __ mean in JavaScript?

__proto__ is a way to inherit properties from an object in JavaScript. __proto__ a property of Object. prototype is an accessor property that exposes the [[Prototype]] of the object through which it is accessed. POSTly is a web-based API tool that allows for fast testing of your APIs (REST, GraphQL).

What is prototype in es6?

The prototype property allows you to add properties and methods to any object (Number, Boolean, String and Date, etc.). Note − Prototype is a global property which is available with almost all the objects. Use the following syntax to create a Boolean prototype.


1 Answers

When you put something on the prototype, every instance of the object shares the same code for the method. They are all using the same function instance.

When you simply put a method on this, every object instance has its own copy of the same method.

Using prototype is much more efficient. Note this is why typically methods are placed on the prototype, since you typically want all instances to use the same method, but properties are placed on the instance itself, because typically you don't want all instances to share the same properties.

For your comment, if you put a method on the constructor function of an object, then you have in effect created a "static" method. No instance of the object will have that method, they all must access it on the constructor function. So in your case, Person.someMethod().

like image 83
hvgotcodes Avatar answered Sep 24 '22 14:09

hvgotcodes