天天看点

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.