1. 程式人生 > >為什麼通用的物件方法要加在原型中

為什麼通用的物件方法要加在原型中

在建構函式中加屬性,原型中加方法。我學面向物件時一直記著的一句話,但為什麼方法要加在原型呢,今天再次看望遠鏡書時終於明白了。

將屬性和方法都寫在建構函式中沒問題,但問題在於每次進行例項化的過程中,重複建立功能不變的方法。

由於方法本質上是函式,其實也就是在堆記憶體中又新建了一個物件空間儲存函式,造成了不必要的資源浪費。

 

解決辦法除了使用原型外,也可以令其指向一個全域性的函式,從而避免重複建立方法。

函式內:

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