解决scheme“这个”引用改变里面的callback?
我一直遇到的问题之一是对this
指针改变的引用。 以下面的例子。 我想创build一个服务器对象,并将相机的分辨率存储为一个属性。 这是不可能的,因为this.resolution
适用于相机callback对象而不是服务器对象的属性。
function Server(options) { this.settings = options.settings; this.camera = options.camera; // Grab camera resolution this.camera.getImageResolution(function(err, data) { this.resolution = data; }); } Server.prototype.start = function() { console.log(this.resolution); // This outputs an undefined variable error }
过去,我通过重命名this
来临时调用函数来解决这个问题。 当我存储一个值时,这不起作用。 我需要通过this
callback,我显然不能这样做。
另外,我不能使用apply
,因为这不会允许camera.getImageResolution
调用它自己的方法。
解决这个问题的最佳途径是什么? 如果我的问题含糊不清,请要求澄清。
function Server(options) { var self = this; self.settings = options.settings; self.camera = options.camera; // Grab camera resolution this.camera.getImageResolution(function(err, data) { self.resolution = data; }); } Server.prototype.start = function () { return this.resolution; } var server = new Server({options: {...}, settings: {...}}); server.camera.getImageResolution(); // after getImageResolution's asynch method has completed server.start() // === data parameter from getImageResolution's asynch method callback