如何从一个对象中访问“this”
我有一个这样的js对象:
let service = function () { this.a = 100; } service.prototype.func = function() { console.log(this.a) } service.prototype.func2 = function () { console.log('func2') this.func(); } service.prototype.obj = { m: { n: { o: function() { this.func2(); }, p: service.prototype.func2.bind(service.prototype) } } }
我想从o或p访问'a',这里是代码:
let s = new service(); console.log(sa) s.func() s.func2() s.obj.mnp() s.obj.mno()
和输出是
100 100 func2 100 func2 undefined test.js:20 this.func2(); ^ TypeError: this.func2 is not a function
任何想法,我怎么可以写o / p正确执行像func2?
这个怎么样?
var service = function() { this_ = this; this.a = 100; } service.prototype.func = function() { console.log(this.a) } service.prototype.func2 = function() { console.log('func2') this.func(); } service.prototype.obj = { m: { n: { o: function() { this_.func2(); }, p: service.prototype.func2.bind(service.prototype) } } } var s = new service(); console.log(sa) s.func() s.func2() s.obj.mnp() s.obj.mno()
更新:
正如Jaromanda X所指出的那样,我正在更新代码来完成OP所要的任务,而没有定义全局variables(我忘记了这一点)。
var service = function(v) { this.a = v; this.obj = this.objFunc(this); } service.prototype.func = function() { console.log(this.a) } service.prototype.func2 = function() { console.log('func2') this.func(); } service.prototype.objFunc = function(self) { return { m: { n: { o: function() { self.func2(); }, p: service.prototype.func2.bind(service.prototype) } } }; } var s = new service(100); var s2 = new service(200); s.func(); s2.func(); s.obj.mno()); s2.obj.mno());
这段代码和OP代码之间的区别在于,obj是每个服务实例的一个属性,而OP的代码将obj设置为服务类的通用属性。
此外,我设置obj属性来调用objFunc类,以便他可以作为s.obj.mno()访问它。 如果我没有,他将不得不作为s.obj()。mno()来访问它。
我希望这是他心中想要的。