Javascript中的原型和this指针

jopen 10年前
1、Javascript中的原型:

原型prototype是Javascript中特有的一个概念。通过原型,Javascript可以实现继承机制。

Javascript本身是基于原型的,每一个对象都有一个prototype属性。而Object对象的prototype属性为null。

下面来看一个使用原型实现继承的例子:

1.1使用原型实现继承:
 function Person(name){      this.name = name;      this.getName = function(){          return this.name;      }  }  function Artist(type){      this.type = type;      this.getType = function(){          return this.type;      }  }  Artist.prototype = new Person("arthinking");  var artist = new Artist("Guitar");  alert(artist.getType());  //本身就有type属性  alert(artist.getName());  //从Person原型链上继承到的属性和方法
2、this指针:

Javascript中的this指针与传统的面向对象中的有些不同。传统的面向对象中this指针在类中声明的,表示对象本身。

Javascript中this表示当前上下文,即调用者的引用。Javascript中this代表的对象不是根据函数的声明而确定的,而是根据的调用而确定的。下面展示了一个函数中的this使用call指定具体代表的对象:

var test1 = {      name : "test1"  }  var test2 = {      name : "test2"  }  function getName(){      return this.name;  //this根据传调用该函数的上下文来确定的,定义该函数时,this指针并不确定  }  alert(getName.call(test1));

这里的call是Function的一个函数。