This和Prototype定義方法的區別
阿新 • • 發佈:2021-01-11
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”節約資源。