javascript - Is it a prototype problem again?
怪我咯
怪我咯 2017-05-19 10:30:56
0
3
540

I don’t understand what is the essential difference between the following two ways of writing?

function Person() {
}

Person.prototype.age = function(n) {
    return n;
}
var person = new Person();
person.age(9);

The above writing method uses the prototype to allow the instantiated object to call the function of the parent class.

The following method does not pass the prototype, but it is exactly the same in usage.

function Person() {
    this.age = function(n) {
        return n;
    }
}
var person = new Person();
person.age(9);

In what aspects are the two comparable? Please advise, thank you!

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(3)
过去多啦不再A梦

There is a difference in memory saving

  • The first way, prototye definition, all descendants share a method definition, which only occupies one space in the memory. No matter how many instances you create, the age method of all instances points to this memory address.

  • The second method is defined in the constructor. Every time an instance is created, the definition of the age method will allocate a space that is exclusive to the instance. As more instances are created, the memory increases proportionally.

In summary, if it is a common method, please put it in the prototype.

習慣沉默

The second way of writing is the constructor pattern, which is easy to use, but the main problem with this method is that each method must be recreated on each instance.
The first prototype pattern approach solves this problem by letting all object instances share the properties and methods it contains.

習慣沉默

Simply put, the functions are the same, except that in most cases the methods are written in the prototype and the properties are written in the constructor, so the first method is more commonly used

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template