天天看點

JavaScript中為何要使用prototype

在javascript學習和工作中,或多或少會接觸一些底層的javascript知識。比如下面四個基本概念:

1.prototype

2.this關鍵字

3.原型繼承

4.javascript閉包

個人覺得的看得越多,技術好像也越來越複雜。之前看完《head first javascript》,這本書裡面講到了this關鍵字和prototype的概念。一下是個人的筆記和了解。

javascript不是真正的面向對象(oop),但是很多開發者嘗試使用編寫java/c#的方法去編寫javascript代碼,一方面是容易了解,另一方面也是後期代碼中更容易維護,更容易調試等友善。

prototype的出現是為了解決在傳統代碼中,我們每建立一個對象執行個體,每個執行個體都會有重複的方法,這樣在建立數量較多的對象執行個體時,代碼備援,占用記憶體多。是以将對象的方法放到類中。稱為:類擁有的方法。class-owned method.

代碼舉例,建立一個blog的程式。每個blog對象有發表時間,内容2個屬性,查找内容,分行高亮資料,顯示詳細時間的三個方法。

//常見的寫法

function blog(body,date){

//properties

this.body=body;

this.date=date;

//methods

this.tostring=function(){

return "["+(this.date.getmonth()+1)+"/"+this.date.getdate()+"/"+

this.date.getfullyear()+"]"+this.body;

};

this.tohtml=function(highlight){

var bloghtml="";

bloghtml+=highlight?"<p style='background-color:#eee;'>":"<p>";

bloghtml+="<strong>"+(this.date.getmonth()+1)+"/"+this.date.getdate()+"/"+

this.date.getfullyear()+"</strong><br/>"+this.body+"</p>";

return bloghtml;

this.containstext=function(text){

return (this.body.tolowercase().indexof(text.tolowercase())!=-1);

}

建立三個對象執行個體:

var blog1=new blog("hello world",new date());

var blog2=new blog("this is a test",new date());

var blog3=new blog("do you like javascript?",new date());

那麼實際上,三個對象都copy對象的三個方法,一個9個方法。通過引入prototype,可以用改進代碼,将對象執行個體的三個共有方法使用prototype添加到“類”blog中。改進後的代碼如下:

//instance property

//instance method

this.showversion=function(){

return "version1.0";

//建立每個對象時,執行個體的屬性和方法都會複制一遍

//return a string repsentation of the blog entry

blog.prototype.tostring=function(){

//return a formatted html

blog.prototype.tohtml=function(highlight){

//check if the blog body content contains a string

blog.prototype.containstext=function(text){

然後建立三個對象執行個體,那麼三個方法都是公用“類”的那一份,是以隻有唯一一份的方法。

後面複雜的原型繼承也使用到了prototype,情況和場景要比這裡複雜,不過個人覺得head first能把為什麼要使用prototype說明白,已經對初學者幫助很大。

小結:

classes vs instances

class properties and methods

類擁有的屬性和方法。通過使用prototype可以為“類”添加屬性和方法。

instance properties and methods

執行個體的屬性和方法,在對象中使用this關鍵字的方法或者屬性都是對象執行個體方法和屬性

own once, run many: class-owned methods only one copy shared for all instances.

use prototype to work at a class-level

prototype"對象"是每個對象的一個隐藏屬性, prototype可以允許你可以在class級别為對象添加屬性和方法。

a class property is stored once in a class but accessible to all instances.