javascript
javascript原型链中 this 的指向
為了弄清楚Javascript原型鏈中的this指向問(wèn)題,我寫了個(gè)代碼來(lái)測(cè)試:
var d = {d: 40};var a = {x: 10,calculate: function (z) {return this.x + this.y + z + this.d},__proto__:d};var b = {y: 20,__proto__: a};var c = {y: 30,__proto__: a};運(yùn)行如下的代碼進(jìn)行測(cè)試:
console.log(b.calculate(30)); // 100 console.log(c.calculate(40)); // 120從這個(gè)結(jié)果中可以看出 this.y 和 this.d 都獲取到了值。但是如何找到值的呢。
翻閱資料得出:this這個(gè)值在一個(gè)繼承機(jī)制中,仍然是指向它原本屬于的對(duì)象,而不是從原型鏈上找到它時(shí),它所屬于的對(duì)象。
? ? 此時(shí)我們得出 b.calculate(30)中的this指的就是 b 對(duì)象。
1. this.x的值首先在 b對(duì)象中找,沒找到,就沿著原型鏈找,在b的原型a中找到了值是10。
2.this.y的值首先在 b對(duì)象中找,找到了,值為20.
? 3.this.d的值首先在b對(duì)象中找,沒找到,就沿著原型鏈找,在b的原型a中也沒找到,然后在a的原型d中找,找到了值是40.
? ? ? 4.此時(shí)運(yùn)算?this.x + this.y + z + this.d=10+20+30+40=100.
? 同理: c.calculate(40) 的值就是 10+30+40+40=120
?此時(shí)我們把代碼再修改下:
var d = {d: 40};var a = {x: 10,calculate: function (z) {console.log(x);console.log(y);console.log(z);console.log(d);return x + y + z + d //去掉了this},__proto__:d};var b = {y: 20,__proto__: a};var c = {y: 30,__proto__: a};在運(yùn)行:
console.log(b.calculate(30))得出結(jié)果:
?此時(shí)在 方法calculate中是沒有定義 x 這個(gè)變量的。 所以就 提示 x is not defined.
轉(zhuǎn)載于:https://www.cnblogs.com/huaan011/p/6812973.html
總結(jié)
以上是生活随笔為你收集整理的javascript原型链中 this 的指向的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 基于Qt的光盘刻录开发
- 下一篇: Lucene5.5.4入门以及基于Luc