为什么通用的对象方法要加在原型中

版权声明:内容多为自言自语,请自行判断有无价值。 https://blog.csdn.net/weixin_41702247/article/details/83381833

在构造函数中加属性,原型中加方法。我学面向对象时一直记着的一句话,但为什么方法要加在原型呢,今天再次看望远镜书时终于明白了。

将属性和方法都写在构造函数中没问题,但问题在于每次进行实例化的过程中,重复创建功能不变的方法。

由于方法本质上是函数,其实也就是在堆内存中又新建了一个对象空间存储函数,造成了不必要的资源浪费。

解决办法除了使用原型外,也可以令其指向一个全局的函数,从而避免重复创建方法。

函数内:

function Person(name){
    this.name=name,
    this.sayName=function(){
        console.log(this.name);
    }
}

var tom=new Person('Tom');
tom.sayName();    //Tom

tom.hasOwnProperty('sayName');    //true

 全局函数对象:

function Person(name){
    this.name=name,
    this.sayName=sayName
}

function sayName(){
    console.log(this.name);
}

var tom=new Person('Tom');
var mary=new Person('Mary');

tom.sayName();    //Tom
mary.sayName();    //Mary

tom.hasOwnProperty('sayName');    //true

原型:

function Person(name){
    this.name=name,
}

Person.prototype.sayName=function(){
    console.log(this.name);
}

var tom=new Person('Tom');
var mary=new Person('Mary');

tom.sayName();    //Tom
mary.sayName();    //Mary

tom.hasOwnProperty('sayName');    //false

猜你喜欢

转载自blog.csdn.net/weixin_41702247/article/details/83381833