简体   繁体   English

如何访问不同对象的属性?

[英]How do I access properties from different objects?

I´m new to objects and OOP and I wanted to know, how I could get an object name and if theres another way to access properties of objects,besides the one that I described below. 我是对象和OOP的新手,我想知道如何获取对象名称以及是否有另一种访问对象属性的方法,除了下面介绍的方法。

Okay, let´s take this example: 好的,让我们举个例子:

function giveMeSomeName() {
    console.log(this)
};

giveMeSomeName();

Console will return the object, which this points to, in this case "Window" 控制台将返回该对象指向的对象,在这种情况下为“窗口”

var myObject = {
    giveMeSomeName: function() {
        console.log(this)
    }
}

Console will return the object, which this points to, in this case "Object" 控制台将返回该对象指向的对象,在这种情况下为“对象”

  1. In this case the referring Object will be "myObject". 在这种情况下,引用对象将是“ myObject”。 Let´s assume I dont have this information, all I have is the console telling me, that this points towards an Object. 假设我没有此信息,而我所拥有的只是控制台告诉我, 指向一个对象。 Is there a way to get the exact name(in this case I would be looking for "myObject") of the object where this is pointing to? 有没有办法得到确切的名称(在这种情况下我会寻找“myObject的”),其中所指向的对象?

Let´s move on to my second question and extend the second code snippet by one line(this.age = "20"): 让我们继续我的第二个问题,并将第二个代码片段扩展一行(this.age =“ 20”):

var myObject = {
    giveMeSomeName: function() {
        console.log(this)
        this.age = "20"
    }
}

If I wanted to access or manipulate "age" in another context IN this case I would go with "myObject.age += 1" for example and it would change the property "age" of the object "myObject" to 21. 如果要在另一个上下文中访问或操作“年龄”,在这种情况下,我将使用“ myObject.age + = 1”,它将对象“ myObject”的属性“ age”更改为21。

  1. Is there another way in terms of syntax to access "age"? 就语法而言,还有另一种方式可以访问“年龄”吗? this.age wont work, since this points to "Window" and not to "myObject"(where "age" is undefined). this.age无法正常工作,因为它指向“ Window”而不是“ myObject”(其中“ age”未定义)。 As you may realised this question correlates with the first one. 您可能已经意识到,这个问题与第一个问题有关。

And to be concrete : 具体来说

I have the following code. 我有以下代码。 How could I access "enemy" in the function "enemyMovement()" (bottom line in the following code)? 如何在函数“ enemyMovement()”中访问“ enemy”(以下代码的下一行)?

var game = new Phaser.Game(500, 200, Phaser.Auto, '', 
    {
        preload: preload,
        create: create,
        update: update
    }
);

function preload() {
    game.load.image('tank', 'assets/tank.png')
    game.load.image('tankEnemy', 'assets/tankEnemy.png')
}

function create() {
    game.stage.backgroundColor = '#3598db'
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.world.enableBody = true;

    this.cursor = game.input.keyboard.createCursorKeys();
    this.tank = game.add.image(200, 75, 'tank')
    this.enemy = game.add.image(0, 0, 'tankEnemy')
}

function update() {
    if (this.cursor.left.isDown) {
        this.tank.position.x -= 3;
    }
    else if (this.cursor.right.isDown) {
        this.tank.position.x += 3;
    }
    else if (this.cursor.up.isDown) {
        this.tank.position.y -= 3;
    }
    else if (this.cursor.down.isDown) {
        this.tank.position.y += 3;
    }

    enemyMovement();
}

function enemyMovement() {
    enemy.position.x += 3;  //how can I access 'enemy' from above?
}

Thanks :) 谢谢 :)

When using functions as the basis for objects, you need to use the function as a "constructor function", which means that you instantiate it using the new keyword. 使用函数作为对象的基础时,需要将函数用作“构造函数”,这意味着您可以使用new关键字实例化它。 Once you do this the usage of the this keyword within the function causes the word to bind to the object variable created during the instantiation. 完成此操作后,在函数中使用this关键字会使单词绑定到实例化期间创建的对象变量。 This is how you create instance properties. 这是创建实例属性的方式。 So: 所以:

 // This funciton is intended to be used to construct distinct instances of objects // Notice that the name is written in Pascal Case to alert others of this fact. function GiveMeSomeName(input) { this.myProp = input; console.log(this.myProp) }; // When using a constructor function, use the `new` keyword to generate the instance // and capture the resulting object in a variable to keep each instance separate from // the next. var myObjectInstance1 = new GiveMeSomeName("foo"); var myObjectInstance2 = new GiveMeSomeName("foo2"); 

Will create two separate instances of your object, each with different data stored in its own instance property. 将创建对象的两个单独的实例,每个实例具有存储在其自己的instance属性中的不同数据。

Also, by convention, functions that are meant to be called as constructor functions should be named using Pascal Case (start with a capital letter) to let others know that it should be called with new and it will return an instance. 同样,按照约定,应使用Pascal Case(以大写字母开头)来命名要构造为函数的函数,以使其他人知道应使用new来调用它,并且它将返回一个实例。

For your particular game code, each element of the game that should encapsulate its own data and behaviors should be an object, so this code: 对于您的特定游戏代码,应该封装自己的数据和行为的游戏的每个元素都应该是一个对象,因此此代码:

function create() {
    game.stage.backgroundColor = '#3598db'
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.world.enableBody = true;

    this.cursor = game.input.keyboard.createCursorKeys();
    this.tank = game.add.image(200, 75, 'tank')
    this.enemy = game.add.image(0, 0, 'tankEnemy')
}

Should either be a constructor function (and called with new ) or it should itself create a new object and return that object (like a factory function would). 应该是构造函数(并用new调用),或者它本身应该创建一个新对象并返回该对象(就像工厂函数一样)。 Here's an example: 这是一个例子:

// This will be a factory function that creates and returns an object instance
function createEnemy() {
    game.stage.backgroundColor = '#3598db'
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.world.enableBody = true;

    function Enemy(){
      this.cursor = game.input.keyboard.createCursorKeys();
      this.tank = game.add.image(200, 75, 'tank')
      this.enemy = game.add.image(0, 0, 'tankEnemy')
    }

    // Create the instance and return it:
    return new Enemy();
}

Then you would simply get your enemy object and use it like this: 然后,您只需获取敌人的对象并像这样使用它:

// Notice here we are NOT using the `new` keyword because the 
// factory function is already doing that internally. We are just
// "catching" the resulting object that is returned from the factory.
var enemy1 = createEnemy();
enemy1.tank = ...

Finally, because all of this hinges on you, the developer, remembering to use the new keyword, JavaScript now includes the object.create() method that allows you to pass an object that will serve as the prototype object and it returns a new instance for you to use. 最后,由于所有这些取决于开发人员,记住了使用new关键字,因此JavaScript现在包含object.create()方法,该方法允许您传递将用作原型对象的对象,并返回一个新实例供您使用。

In general I suggest you have a deeper look to Prototypes . 一般而言,我建议您对“ 原型”有更深入的了解。

In your particular case try extending 'game' object with 'enemyMovement' function: 在您的特定情况下,请尝试使用“ enemyMovement”功能扩展“游戏”对象:

game.enemyMovement = function() {
    this.enemy.position.x += 3;
}

and change 'update' function: 并更改“更新”功能:

    ...
    this.enemyMovement();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何访问解析对象属性? - How do I access a Parse objects properties? 如何访问放置了javascript对象的对象的属性? - How do I access the properties of objects that are placed a javascript object? 如何访问 console.table() 中的嵌套对象属性? - How do I access nested objects properties in console.table()? 如何将 map 对象数组转换为 Redux Slice 中的不同对象(具有不同属性)? - How do I map an array of objects to different objects (with different properties) in a Redux Slice? 如何从模板访问对象的属性? - How Do I Access an Object's Properties From a Template? 如何使用JavaScript创建对象,以便以后可以访问它们的属性? - How do I create Objects in Javascript, so I can later access their properties? 我的基本问题是如何访问对象列表中单个 object 的属性或方法? - My basic question is how do I access the properties or methods of an individual object in a list of objects? 如何从json访问对象以自动下拉 - How do I access the objects from json to automate dropdown 如何从Chrome扩展程序访问所有窗口对象? - How do I access ALL window objects from a Chrome extension? 在使用“this”关键字的方法中,如何从其他属性访问对象属性? - How do I access the object properties from other properties, while within a method using the 'this' keyword?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM