在嵌套函数中使用`this`作为父函数

Nyx*_*nyx 4 javascript oop jquery class object

在Apple"类"中,嵌套函数如何countSeeds()检索值this.price

jsfiddle: http ://jsfiddle.net/VGqEa/

Apple = function() {
    this.price = 17

    this.cutOpen = function() {

        console.log(this.price);
        countSeeds();

        function countSeeds() {
            console.log(this.price);
        }
    }        
}


var apple = new Apple();
apple.cutOpen();
Run Code Online (Sandbox Code Playgroud)

产量

17
undefined
Run Code Online (Sandbox Code Playgroud)

Tha*_*yne 8

放在var self = thisApple的顶部,然后在嵌套函数中将其称为self.

即:

Apple = function() {
    var self = this;
    this.price = 17

    this.cutOpen = function() {

        console.log(this.price);
        countSeeds();

        function countSeeds() {
            console.log(self.price);
        }
    }        
}


var apple = new Apple();
apple.cutOpen();
Run Code Online (Sandbox Code Playgroud)

您也可以将该self=this语句放在this.cutOpen的开头,因为这仍然会引用cutOpen中的Apple对象(因为它是Apple的一种方法).

更新

大多数常绿浏览器现在都支持箭头功能,因此您可以像下面这样编写它:

Apple = function() {
    var self = this;
    this.price = 17

    this.cutOpen = function() {

        console.log(this.price);
        let countSeeds = () => {
            console.log(this.price);
        };
        countSeeds();
    }        
}
Run Code Online (Sandbox Code Playgroud)

这在IE11或其他旧版浏览器中不起作用,除非您使用某种转换器来定位较旧的javascript.