芝华塔*_*塔尼欧 4 javascript closures
如何从闭包中获取一个对象,这与我混淆,这是一个问题:
var o = function () {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function (key) {
return person[key]
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题:如何在person不更改源代码的情况下获取原始对象.
Jon*_*lms 10
var o = function() {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function(key) {
return person[key]
}
}
}
Object.defineProperty(Object.prototype, "self", {
get() {
return this;
}
});
console.log(o().run("self")); // logs the objectRun Code Online (Sandbox Code Playgroud)
这个工作过程中的所有对象继承Object.prototype,因此,你可以插入一个getter它,它通过访问对象this,那么你可以使用暴露的run方法来执行吸气.
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |