林芝网站建设,门户网站源码,网站制作机构,网站托管..为了弄清楚Javascript原型链中的this指向问题#xff0c;我写了个代码来测试#xff1a; 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};运行如下的代码…为了弄清楚Javascript原型链中的this指向问题我写了个代码来测试 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};运行如下的代码进行测试 console.log(b.calculate(30)); // 100
console.log(c.calculate(40)); // 120从这个结果中可以看出 this.y 和 this.d 都获取到了值。但是如何找到值的呢。 翻阅资料得出this这个值在一个继承机制中仍然是指向它原本属于的对象而不是从原型链上找到它时它所属于的对象。 此时我们得出 b.calculate(30)中的this指的就是 b 对象。 1. this.x的值首先在 b对象中找没找到就沿着原型链找在b的原型a中找到了值是10。 2.this.y的值首先在 b对象中找找到了值为20. 3.this.d的值首先在b对象中找没找到就沿着原型链找在b的原型a中也没找到然后在a的原型d中找找到了值是40. 4.此时运算 this.x this.y z this.d10203040100. 同理: c.calculate(40) 的值就是 10304040120 此时我们把代码再修改下 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};在运行 console.log(b.calculate(30))得出结果 此时在 方法calculate中是没有定义 x 这个变量的。 所以就 提示 x is not defined.转载于:https://www.cnblogs.com/huaan011/p/6812973.html