This和Prototype
this 是指代上下文中的this對(duì)象
-
利用this實(shí)現(xiàn)的方法,可以訪問(wèn)類(lèi)中的私有變量和私有方法。而利用原型對(duì)象實(shí)現(xiàn)的方法,無(wú)法訪問(wèn)類(lèi)中的私有變量和方法
function Person(x){ this.x = x; //變量x var a = "this is private"; //這個(gè)是Person中的私有變量 //this 實(shí)現(xiàn)的方法 this.hello = function() { console.log(a) } } //通過(guò)prototype實(shí)現(xiàn)的原型對(duì)象上的方法 Person.prototype.say = function(){ console.log(a) } // 生成實(shí)例 var person1 = new Person(1) person1.hello() // "this is private" person1.say() // ReferenceError: a is not defined -
實(shí)例訪問(wèn)對(duì)象的屬性或者方法時(shí),將按照搜索原型鏈prototype chain的規(guī)則進(jìn)行。首先查找自身的靜態(tài)屬性、方法,繼而查找構(gòu)造上下文的可訪問(wèn)屬性、方法,最后查找構(gòu)造的原型鏈。
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" “this”和“prototype”定義的另一個(gè)不同點(diǎn)是在內(nèi)存中占用空間不同。使用“this”關(guān)鍵字,實(shí)例初始化時(shí)為每個(gè)實(shí)例開(kāi)辟構(gòu)造方法所包含的所有屬性、方法和所需空間,而使用prototype定義的,由于“prototype”實(shí)際上是指向父級(jí)的引用,因此在初始化和存儲(chǔ)上比“this”節(jié)約資源。