繁体   English   中英

javascript prototype var未定义,但我不确定为什么。

[英]javascript prototype var is undefined, but I'm not sure why.

我以为我是用JavaScript来“搞定”的,然后遇到了这种情况。 我不知道为什么__sfcont的值未定义。

var __container = "It contains ";

function myObject() {
  var temp = 'temp';
}

myObject.prototype = {
  constructor: myObject,
  searchingFor: {
    __sfcont: "a div block ",
    label: this.__sfcont + "and a label.",
    dropdown: this.__sfcont + "and a dropdown."
  }
};

var myObj = new myObject();

console.log(myObj.searchingFor.label);  

预期的结果将是It contains a div block and a label. 但是我越来越undefinedand a label.

在执行this.__sfcont + "and a label.",this不是您期望的。 这不是searchingFor尚未构造还,但其中的背景下myObject.prototype = { ... }正在执行。 该上下文没有__sfcont属性。

使label (以及dropdown )成为一种方法:

label: function() { this.__sfcont + "and a label."; },
...

console.log(myObj.searchingFor.label());  

初始化时无法访问对象属性。 您可以定义变量,然后再使用它:

var __sfcont = "a div block ";
myObject.prototype = {
  constructor: myObject,
  searchingFor: {
    __sfcont: __sfcont,
    label: __sfcont + "and a label.",
    dropdown: __sfcont + "and a dropdown."
  }
};

您也可以使用吸气剂

myObject.prototype = {
  constructor: myObject,
  searchingFor: {
    __sfcont: "a div block ",
    get label() {
      return this.__sfcont + "and a label"
    }
  }
};

console.log(myObject.searchingFor.label)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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