Javascript中的Prototype到底是啥


 

Javascript也是面向對象的語言,但它是一種基於原型Prototype的語言,而不是基於類的語言。在Javascript中,類和對象看起來沒有太多的區別。

 

通常,這樣創建一個對象:

 

function person(name){
    this.sayHi = function(){
        alert('hi ' + this.name);
    }
    this.name = name;
}

var p = new person("dan");
p.sayHi();

 


以上,使用new關鍵字,通過對象(函數也是特殊對象)創建一個對象實例。

在基於類的語言中,屬性或字段通常都是在類中事先定義好了,但在Javascript中,在創建對象之后還可以為類添加字段。

 

function animal(){}
var cat = new animal();
cat.color = "green";

 

以上,color這個字段只屬於當前的cat實例。

對於后加的字段,如果想讓animal的所有實例都擁有呢?

--使用Prototype

 

function animal(){}
animal.prototype.color= "green";
var cat = new animal();
var dog = new animal();
console.log(cat.color);//green
console.log(dog.color);//green

 


通過Prototype不僅可以添加字段,還可以添加方法。

 

function animal(){}
animal.prototype.color= "green";
var cat = new animal();
var dog = new animal();
console.log(cat.color);//green
console.log(dog.color);//green

animal.prototype.run = funciton(){
    console.log("run");
}
dog.run();

 

原來通過prototype屬性,在創建對象之后還可以改變對象的行為。

比如,可以為數組這個特殊對象添加一個方法。

 

Array.prototype.remove = function(elem){
    var index = this.indexof(elem);
    if(index >= 0){
        this.splice(index, 1);
    }
}

var arr = [1, 2, 3]    ;
arr.remove(2);

 

除了通過prototype為對象定義屬性或方法,還可以通過對象的構造函數來定義類的屬性或方法。

 

function animal(){
    this.color = "green";
    this.run = function(){
        console.log("run");
    }
}

var mouse = new animal();
mouse.run();

 

以上做法的也可以讓所有的animal實例共享所有的字段和方法。並且還有一個好處是可以在構造函數中使用類的局部變量。

 

function animal(){
    var runAlready = false;
    this.color = "green";
    this.run = funciton(){
        if(!runAlreadh){
            console.log("start running");
        } else {
            console.log("already running")
        }
    }
}

 

其實,一個更加實際的做法是把通過構造函數結合通過prototype定義一個類的字段和行為。

 

function animal(){
    var runAlready = false;
    this.run = function(){
        if(!runAlready){
            console.log('i am running');
        } else {
            console.log("i am already running");
        }
    }
}

animal.prototype.color = '';
animal.prototype.hide = funciton(){
    console.log("");
}

var horse = new animal();
horse.run();
horse.hide();

 

Prototype允許我們在創建對象之后來改變對象或類的行為,並且這些通過prototype屬性添加的字段或方法所有對象實例是共享的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM