老生常谈Javascript中的原型和this指针

2019-11-29,,,

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的一个函数。

以上就是小编为大家带来的老生常谈Javascript中的原型和this指针全部内容了,希望大家多多支持北冥有鱼~

您可能感兴趣的文章:

  • 对JavaScript中this指针的新理解分享
  • Javascript this指针
  • 浅谈JavaScript中的this指针和引用知识
  • 小议Javascript中的this指针
  • 你必须知道的Javascript知识点之"this指针"的应用
  • 探寻JavaScript中this指针指向

《老生常谈Javascript中的原型和this指针.doc》

下载本文的Word格式文档,以方便收藏与打印。