gpt4 book ai didi

javascript 原型(prototype) var 未定义,但我不确定为什么。

转载 作者:行者123 更新时间:2023-11-30 07:07:53 25 4
gpt4 key购买 nike

我以为我正在使用 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);

预期的结果是它包含一个 div block 和一个标签。但是我得到了 undefined 和一个标签。

最佳答案

this.__sfcont + "and a label.",执行的时候,this并不是你所期望的。不是尚未构造的searchingFor,而是myObject.prototype = { ... }正在执行的上下文。该上下文没有 __sfcont 属性。

label(以及dropdown)设为一个方法:

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

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

关于javascript 原型(prototype) var 未定义,但我不确定为什么。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37330846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com