gpt4 book ai didi

Javascript: self 和这个

转载 作者:数据小太阳 更新时间:2023-10-29 04:35:12 26 4
gpt4 key购买 nike

谁能解释为什么我对 self 和 this 有不同的值(value)观?其中 self 是对此的引用。

function Parent(){
var self = this;
this.func = function(){
// self.a is undefined
// this.a is 'Test'
console.log(self.a, this.a);
}
}

function Child(x){
this.a = x;
}

Child.prototype.__proto__ = new Parent;
var ch = new Child('Test');
ch.func();

我一直在项目中使用 self,这是我第一次遇到这个问题。

最佳答案

这是因为 self 引用了 Parent 的一个实例,但是只有 Child 的实例有一个 a属性(property)。

function Parent(){
var self = this; // this is an instance of Parent
this.func = function(){
console.log(self.a, this.a);
}
}

function Child(x){
this.a = x; // Instances of Child have an `a` property
}

Child.prototype.__proto__ = new Parent;
var ch = new Child('Test');

ch.func(); // Method called in context of instance of Child

因此,当您在 Child 的实例上调用 func 时,this 会引用该实例。这就是为什么 this.a 会在 func 中为您提供正确的值。

关于Javascript: self 和这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15063756/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com