从原型函数访问属性

从原型函数访问属性

本文介绍了从原型函数访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重用旧应用程序(游戏),因此可以同时运行多个游戏.由于这个原因,我已将属性更改为this.propery",它们在我的应用程序中随处可见.但是,唯一可以访问属性的原型函数是startGame".我已经尝试过this.bricks"和Game.bricks",但是当试图在startGame"的任何其他函数中访问它们时,两者都未定义.

I'm reusing an old application (a game) so it's possible to run several games at ones.By that reason I've changed the properties to "this.propery", which are used everywhere in my application.However, the only prototype function that can access the properties is "startGame".I have tried both "this.bricks" and "Game.bricks", but both are undefined when trying to reach them in any other function that "startGame".

对我有什么建议吗?

var game = new Game();
game.startGame();

Game = function(){
this.bricks = 2;
this.checkOddEven = 0;
    ...
}


Game.prototype.startGame = function() {
    console.log(this.bricks) <- 2
    console.log(Game.bricks) <- 2

// Code goes here...

    Game.prototype.renderTiles()
}

Game.prototype.renderTiles = function() {

// code goes here...

    console.log(this.bricks) <- undefined
    console.log(Game.bricks) <- undefined

}

... 其他原型函数也是如此.

... the same goes for the other prototype functions.

推荐答案

您以错误的方式调用 renderTiles.this 将引用 Game.prototype 而不是 game(Game 实例).

You are calling renderTiles in the wrong way. this will refer to Game.prototype instead of game (the Game instance).

调用它:

this.renderTiles();

this 在函数内部引用什么取决于函数的调用方式.MDN 提供了一篇好文章 关于那个.

What this refers to inside a function depends on how the function is called. MDN provides a good article about that.

FWIW:

只要您不直接为 Game 函数分配属性,Game.bricks 也应该是 undefined,无论在哪里您访问它以及调用该函数的方式.

As long as you are not assigning properties directly to the Game function, Game.bricks should be undefined as well, not matter where you access it and how you call the function.

这篇关于从原型函数访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 18:29