[英]JavaScript - Can I get the parent object of a method?
我想知道是否可以獲取方法的父對象-像這樣:
ImageAsset = function (path) {
this.ready = false; // I want the image.onload function to change this variable.
this.image = new Image;
this.image.onload = function () {
thisParent.ready = true;
};
this.path = path;
this.image.src = this.path;
};
有什么辦法可以做到嗎? 謝謝!
您可以使用變量
ImageAsset = function (path) {
var that = this; // store the value of "this"
this.ready = false;
this.image = new Image;
this.image.onload = function () {
that.ready = true;
};
this.path = path;
this.image.src = this.path;
};
我會說:
ImageAsset = function (path) {
this.ready = false; // I want the image.onload function to change this variable.
this.image = new Image;
var parent = this;
this.image.onload = function () {
parent.ready = true;
};
this.path = path;
this.image.src = this.path;
};
通常有兩種方法可以做到這一點。
this.image.onload = function () {
this.parent.ready = true;
}.bind(this);
注意, bind
僅適用於某些瀏覽器 。 所以你proabaly要使用填充工具 ,所以你可以在所有的瀏覽器使用綁定。 而且,許多Javascript框架都提供了bind
函數的等效項。 例如, jQuery提供proxy 。
this.image.onload = $.proxy(function () {
this.parent.ready;
}, this);
var parent = this;
this.image.onload = function () {
parent.ready = true;
};
就個人而言,我傾向於選擇選項1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.