星空网 > 软件开发 > Java

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);//greenconsole.log(dog.color);//green

 


通过Prototype不仅可以添加字段,还可以添加方法。

 

function animal(){}animal.prototype.color= "green";var cat = new animal();var dog = new animal();console.log(cat.color);//greenconsole.log(dog.color);//greenanimal.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属性添加的字段或方法所有对象实例是共享的。

 




原标题:Javascript中的Prototype到底是啥

关键词:JavaScript

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

独立站是什么意思:https://www.goluckyvip.com/tag/30745.html
独立站收单:https://www.goluckyvip.com/tag/30746.html
独立站收款通道:https://www.goluckyvip.com/tag/30747.html
独立站收款怎么解决:https://www.goluckyvip.com/tag/30748.html
独立站推广方案:https://www.goluckyvip.com/tag/30749.html
你开PPC广告:https://www.goluckyvip.com/tag/3075.html
南京浦口都有什么好玩的地方 南京浦口都有什么好玩的地方推荐:https://www.vstour.cn/a/363180.html
永康白云风景区怎么走 白云山风景区怎么去??:https://www.vstour.cn/a/363181.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流