This和Prototype定义方法的区别

This和Prototype

this 是指代上下文中的this对象

1.利用this实现的方法,可以访问类中的私有变量和私有方法。而利用原型对象实现的方法,无法访问类中的私有变量和方法

function Person(x){
  this.x = x; //变量x
  var a = "this is private";  //这个是Person中的私有变量
  //this 实现的方法
  this.hello = function() {
    console.log(a)
  }
}
//通过prototype实现的原型对象上的方法
Person.prototype.say = function(){
  console.log(a)
}
// 生成实例
var person1 = new Person(1)
person1.hello()         // "this is private"
person1.say()           // ReferenceError: a is not defined

2.实例访问对象的属性或者方法时,将按照搜索原型链prototype chain的规则进行。首先查找自身的静态属性、方法,继而查找构造上下文的可访问属性、方法,最后查找构造的原型链。

function Test(){
  this.test = function() {
    alert("defined by this")
  }
}

Test.prototype.test = function() {
  alert("defined by prototype")
}
var _o = new Test()
_o.test() //"defined by this"

3.“this”和“prototype”定义的另一个不同点是在内存中占用空间不同。使用“this”关键字,实例初始化时为每个实例开辟构造方法所包含的所有属性、方法和所需空间,而使用prototype定义的,由于“prototype”实际上是指向父级的引用,因此在初始化和存储上比“this”节约资源。

posted @ 2021-01-11 11:18  Homegu  阅读(349)  评论(0编辑  收藏  举报