【问题标题】:Cannot read property "texture" from undefined无法从未定义中读取属性“纹理”
【发布时间】:2014-07-06 16:52:56
【问题描述】:

我知道这是一个非常常见的问题。我从 undefined 得到一个无法读取属性“纹理”。对不起,我对 javascript 很陌生。

我的代码的javascript部分如下

this.createTexture=function(Texturename,width,height){
  this.Texture[Texturename]=gl.createTexture();
  this.Texture[Texturename].name=Texturename;
  this.Texture[Texturename].width=width;
  this.Texture[Texturename].height=height;
  return this.Texture[Texturename,width,height];
}

我正在尝试在 webgl 部分中创建我的纹理。

如何在 webgl 中调用 createTexture?我可以在其中输入纹理名称、宽度和高度并让该功能正常工作。我知道这不仅会创建纹理,而且只是一个简单的示例。我试过了,但是可以

function exampleTexture(){
Texture.createTexture("moon",1024,1024);
}

上面写着我的错误

this.Texture[Texturename]=gl.createTexture();

谢谢

【问题讨论】:

  • Texture.Texture 存在吗?您将获得this.Texture,而this 是调用其方法的对象的值。对于Texture.createTexturethis 的值为Texture,所以this.TextureTexture.Texture。我不完全理解您的代码的作用,因此我无法提出解决方案。也许你想做Texture[Texturename],在这种情况下你应该做this[Texturename]

标签: javascript html webgl


【解决方案1】:

this 引用的对象似乎没有Texture 属性。在这种情况下:

this.createTexture=function(Texturename,width,height){
  // use this.Texture if available, otherwise init it as an empty object
  this.Texture = this.Texture || {};

  this.Texture[Texturename]=gl.createTexture();
  this.Texture[Texturename].name=Texturename;
  this.Texture[Texturename].width=width;
  this.Texture[Texturename].height=height;
  return this.Texture[Texturename,width,height];
}

注意命名约定:在 JS 中,camelCase 通常用于变量,PascalCase 用于构造函数。所以我会将this.Texture 重命名为this.textures,将Texturename 重命名为textureName

【讨论】:

    猜你喜欢
    • 2014-12-24
    • 2020-04-06
    • 1970-01-01
    • 2014-07-31
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    相关资源
    最近更新 更多