简体   繁体   English

我可以向当前的“ this”对象添加属性吗? 怎么样?

[英]Can I add a property to the current “this” object? How?

I am checking a this.hash property onClick of tab but onload hash doesn't exist, Can I add hash property onLoad to let this condition pass through? 我正在检查tab的this.hash属性onClick,但是onload哈希不存在,我可以添加哈希属性onLoad来让这种情况通过吗? So self.$("first").ready(renderPage) is called onLoad and I am trying to add this.hash to it so it passes the condition in renderPage(). 所以self。$(“ first”)。ready(renderPage)称为onLoad,我试图将this.hash添加到它,以便它通过renderPage()中的条件。

 render : function () {
        self = this;
        renderPage = function () {
                            console.log("this.hash : " + this.hash);

                            if (this.hash) { // this.hash is only present when tab is clicked onLoad its undefined
                               //do some stuff
                                getTabClicked(this.hash);
                            }
                            buildString();

                            ajaxData.callAPI(function (data) {
                             // process data and render output;
                            });
                     }
         onloadCall = function () {
                            $(self.el).html(self.template());
                            self.$(tab).html(self.templateFlyout());
                            self.$("#allTabs").tabs().addClass("xyz");
                            self.$("#first").tabs();
                            self.$("#second").tabs();
                            //this.hash = "first"; // but it gives error this is undefined.
                            self.$("first").ready(renderPage); // I want to add this.hash before this call
                            self.$("[id^=tabs-]").click(renderPage);
                            onMenuChange();
                        },

                        readJson = function () {
                            $.getJSON("./js/data/myJson.json", function (data) {
                                jsonData = data;
                                onloadCall();
                            });
                        };

            readJson();

            return this;
        }

Yes, easily. 是的,很容易。

this.newProperty = value;
// Or
this[newProperty] = value;

this is defined by the context of the current function. this由当前函数的上下文定义。 If you want to access the same definition of this outside the function it's used in, you have to know what that definition is. 如果您想访问相同的定义this它的使用在功能外,你必须知道的定义是什么。 In your case, it looks like the definition is document , given that you say the context is [#Object HTMLDocument] . 在您的情况下,假设上下文是[#Object HTMLDocument] ,则定义似乎是document So, to add a hash property to that version of this is simple: 因此,向该版本的hash属性添加hash很简单:

// instead of
this.hash = "first";
// use
document.hash = "first";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM