好的,这是一个非常简单的 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.protocol
和this.host
都是未定义的。为什么会这样?
最佳答案
在内部,JavaScript 对象是基于哈希算法构建的。因此,它们的键在逻辑上可能不会按照我们定义它们的顺序出现。在这种情况下,fullPath
首先被定义,当赋值时,它取决于尚未定义的 partOne
和 partTwo
.这就是为什么在定义 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();
这种方法的优点是,您可以动态自定义对象的创建。例如,您可以像这样传递 protocol
或 host
值
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/