Javascript OOP可以';得不到财产
我试图将代码重写为面向对象的方法,但遇到了一些问题。 有一个例子:Javascript OOP可以';得不到财产,javascript,oop,Javascript,Oop,我试图将代码重写为面向对象的方法,但遇到了一些问题。 有一个例子: var counter = { column: { estimation: "tr td:nth-child(3)", worked: "tr td:nth-child(4)", ratio: "tr td:nth-child(5)", difference: "tr td:nth-child(6)" }, columnLength : funct
var counter = {
column: {
estimation: "tr td:nth-child(3)",
worked: "tr td:nth-child(4)",
ratio: "tr td:nth-child(5)",
difference: "tr td:nth-child(6)"
},
columnLength : function display(){
return $(this.column.estimation).length;
},
好的,它起作用了!
但如果我写的几乎相同,但不是在函数中:
var counter = {
column: {
estimation: "tr td:nth-child(3)",
worked: "tr td:nth-child(4)",
ratio: "tr td:nth-child(5)",
difference: "tr td:nth-child(6)"
},
columnLength : $(this.column.estimation).length
},
没有,有错误:
列未声明
为什么它必须在功能上?
Thx提前。问题是,当您在jQuery选择器中使用
this
时,$(…)
的值是全局对象窗口
而不是对象计数器
。因此,基本上,您试图调用对象窗口的property列window.column
,使其不存在
如果运行以下代码,您将看到this的值是多少:
var counter = {
column: {
estimation: "tr td:nth-child(3)",
worked: "tr td:nth-child(4)",
ratio: "tr td:nth-child(5)",
difference: "tr td:nth-child(6)"
},
columnLength: console.log(this)
}
那么,为什么会发生这种情况
因为当您将已执行的函数分配给文本对象的参数时,该函数将在全局上下文中执行
有关使用此的更多信息:可能重复的