爲什麼通用的對象方法要加在原型中

原文鏈接: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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章