簡體   English   中英

JavaScript-我可以獲取方法的父對象嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM