'this'在这种情况下如何工作?

这个问题在这里已经有了答案:

  • 嵌套函数中的Javascript“this”指针7个答案

  • mainState是一个对象文字。 'prototype'是javascript中用于原型继承的函数对象的一个​​属性。 Javascript原型


    有一件事总是帮助我记住this将是什么,以查找谁在调用函数,请检查此代码段

    var sayHi = function() { console.log(this.name) }
    
    var yoda = { name: "Yoda", sayHi: sayHi }
    var darthVader = { name: "Anakin Skywalker", sayHi: sayHi }
    
    // the `this` here will be the yoda object
    yoda.sayHi()
    // the `this` here will be the darthVader object
    darthVader.sayHi()
    
    window.name = "Global name"
    // here, since nothing was specified, the object is the global object, or the window on browsers, this the same as "window.sayHi()"
    sayHi()

    如果你想在原型上使用你的方法,你可以创建一个MainState构造函数,并附上你的原型方法:

    function MainState(game) { 
        this.game = game;
    }
    
    MainState.prototype.create = function() {
        this.bird = this.game.add.sprite(100, 245, 'bird');
    };
    
    MainState.prototype.myFunction = function() { };
    
    // etc.
    
    var mainState = new MainState(game);
    
    mainState.myFunction();
    
    链接地址: http://www.djcxy.com/p/94903.html

    上一篇: How is 'this' working in this context?

    下一篇: How to use 'this' in nested object?