javascript - 使用 `this` 的 JS 对象给出了未定义的结果

标签 javascript oop

好的,这是一个非常简单的 JS 对象。三个属性是字符串,第四个是函数。

var myStringBuilder = {
  protocol: "http://",
  host: "www.mysite.com",
  fullPath: this.protocol + this.host + "/just/for/fun/",
  getFullString: function() {
    return this.fullPath;
  }
}

console.log(myStringBuilder.getFullString());  // Returns "NaN/just/for/fun"

fullPath中,this.protocolthis.host 都是未定义的。为什么会这样?

jsfiddle

最佳答案

在内部,JavaScript 对象是基于哈希算法构建的。因此,它们的键在逻辑上可能不会按照我们定义它们的顺序出现。在这种情况下,fullPath 首先被定义,当赋值时,它取决于尚未定义的 partOnepartTwo .这就是为什么在定义 fullPath 时它们是 undefined 的原因。

如果你必须像这样构造一个对象,我会推荐一个构造函数,像这样

function MyStringBuilder() {
    this.protocol = "http://";
    this.host = "www.mysite.com";
    this.fullPath = this.protocol + this.host + "/just/for/fun/";
}

MyStringBuilder.prototype.getFullString = function() {
    return this.fullPath;
}

myStringBuilder();

这种方法的优点是,您可以动态自定义对象的创建。例如,您可以像这样传递 protocolhost

function MyStringBuilder(protocol, host) {
    this.protocol = protocol || "http://";
    this.host     = host     || "www.mysite.com";
    this.fullPath = this.protocol + this.host + "/just/for/fun/";
}

通过此更改,您应该能够在运行时决定协议(protocol)主机

关于javascript - 使用 `this` 的 JS 对象给出了未定义的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23318905/

相关文章:

javascript - 邮政编码和城市列表,excel 方舟还是数据库?

Java 3-SUM 代码表现异常

c# - 我应该如何合并这两种方法?

python - 构造函数重载Python

javascript - 一旦值发生变化(客户端)如何直接更新值?

javascript - 如何在javascript中将数组转换为没有逗号和空格分隔的字符串而不连接?

javascript - 如何从 WinJS iframe Windows 8 应用程序形成 POST 到 Paypal?

javascript - 提取特定子项以控制它们的渲染位置是否是一种反模式?

C#调用另一个Form的方法

javascript - Pixi.js 如何将 moveTo 与 OOP 对象一起使用?