简体   繁体   中英

JS object using `this` gives an undefined result

Ok here is a very simple JS object. Three attributes are strings, the fourth is a function.

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"

In fullPath , this.protocol and this.host are both undefined. Why does this happen?

jsfiddle

Internally JavaScript objects are constructed based on a hashing algorithm. So, they keys may not logically appear in the order we define them. In this case, fullPath gets defined first and when the value is assigned, it depends on partOne and partTwo where they havn't got defined yet. That is why they are undefined while defining fullPath .

If you must construct an Object like this, I would recommend a constructor function, like this

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();

The advantage of this method is that, you can customize the object creation dynamically. For example, you can pass protocol or host values like this

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

with this change, you should be able to decide the protocol and host at runtime.

To get around part of the hash being undefined, you can use functions instead of calculated values. This will delay evaluation.

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

如果我在以前的答案的所有有价值的信息,同意回答对问题的精确点,该fullPath属性定义不正确,因为它不是在一个函数上下文初始化,所以this并不是指对象myStringBuilder。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM