[英]JavaScript Classes: Accessing method from within an Object's function property
[英]JavaScript syntax for accessing a property of an object from within the object scope
我有這個功能:
function Entity(textureSrc)
{
var entity = {
texture: textureSrc,
position: { x: 0, y: 0 },
test: this.texture,
construct: function()
{
alert(this.test);
}
}
return entity;
}
然后這個測試代碼:
var testObject = Entity("Textures/AirTexture.png");
testObject.construct();
作為測試,我在為entity
創建新屬性時嘗試利用entity.texture
的值 - 我無法弄清楚執行此操作的語法是什么。
我試過了:
test: this.texture
test: entity.texture
test: texture
但這些都不起作用; 他們都導致undefined
。
另外 - 在construct
方法中使用this
詞是否正確用於訪問test
或者這應該以不同方式完成?
在“測試”行上,“this”尚不存在(因為你正在定義它)。
它,然而,有效的使用這個在構造函數,因為當該功能正在評估, 這將存在(以及將指向你期望它,除非你重新綁定功能是什么)。
正如科爾賓所說的那樣 - 讀一篇約翰的舊帖子簡單的“類”實例化可能仍然是一個好主意
應該指向一個簡單快速的對象創建方法:
function Entity(textureSrc) {
if ( !(this.instanceof Entity) ) {
return new Entity(textureSrc)
}
this.texture = textureSrc,
this.position = {
x: 0,
y: 0
}
}
Entity.prototype = {
construct: function () {
alert(this.texture)
}
}
通過這種方式,您可以按照您描述的相同方式實體:
var testObject = Entity("Textures/AirTexture.png");
testObject.construct();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.