【发布时间】:2018-04-14 04:49:53
【问题描述】:
我希望实现以下目标。
HTMLSpanElement.prototype.testNS = {
_this: this,
testFunc: function() {
console.log(this.innerHTML) //undefined as expected as this is the testFunc object
},
testFunc2: function() {
console.log(this._this) //Window object
}
}
在这种情况下,我的目标是直接向 span 元素添加一些辅助函数。
所以,如果我有以下情况:
<span>test</span>
我可以找到跨度并调用此代码以返回“测试”
spanElement.testNS.testFunc()
我知道当我这样做时,函数会保留其父级的范围......
HTMLSpanElement.prototype.testFunc = function() {
console.log(this.innerHTML)
}
但是我正在尝试稍微组织代码,并在添加函数时更清楚地显示函数的来源,当我执行普通 JSON 对象时,我似乎无法找到保留范围的方法将 this 作用域抓取到 _this: this 中,它只返回“window”的全局作用域。
【问题讨论】:
-
“因为这是 testFunc 对象”
this永远不会引用函数对象本身。如果调用函数为spanElement.testNS.testFunc(),则引用panElement.testNS。
标签: javascript namespaces prototype