简体   繁体   English

这个JS怎么了?

[英]whats wrong with this JS?

There is any interesting article which warns about JS problems. 有任何有趣的文章警告JS问题。

However, notice #2: 但是,请注意#2:

<input type="button" value="Gotcha!" id="MyButton" >
<script>
var MyObject = function () {
    this.alertMessage = "Javascript rules";
    this.ClickHandler = function() {
          alert(this.alertMessage );
      }
}();

</script>

Notice the self executing function by () at the end. 最后请注意()的自我执行功能。 However I'm pretty sure the this.xxx is used when doing new MyObject() . 但是我很确定在做new MyObject()时会使用this.xxx He wrote : 他写了 :

If you call MyObject.ClickHandler(); 如果调用MyObject.ClickHandler(); you will get a popup saying "Javascript rules". 您将看到一个弹出窗口,显示“ Javascript规则”。

and his sample doesn't work. 而且他的样本无效。 I've tried MyObject.ClickHandler() and got an error...(Cannot call method 'ClickHandler' of undefined) 我尝试了MyObject.ClickHandler()并收到一个错误...(无法调用未定义的方法'ClickHandler')

How can I make MyObject.ClickHandler() work ? 如何使MyObject.ClickHandler()工作?

You are missing the new keyword. 您缺少new关键字。 Currently, this refers to window and ClickHandler is available through window.ClickHandler . 当前, this是指window并且可以通过window.ClickHandler获得ClickHandler

When using the new keyword, a new object is created and the this keyword will refer to that newly created object. 使用new关键字时,将创建一个新对象,并且this关键字将引用该新创建的对象。 That is why the ClickHandler method will be added to MyObject below: 这就是将ClickHandler方法添加到以下MyObject

var MyObject = new (function () {
    this.alertMessage = "Javascript rules";
    this.ClickHandler = function () {
        alert(this.alertMessage);
    };
})();

Be careful when doing something like: 进行以下操作时要小心:

document.getElementById("MyButton")
    .addEventListener("click", MyObject.ClickHandler, false);

addEventListener makes this refer to the object on which the event listener was assigned. addEventListener使得this指在其上被分配的事件侦听器的对象。 See also bind for changing the this scope. 另请参见bind以更改this范围。

EDIT: Zoiks, Lekensteyn hit the nail on the head. 编辑: Zoiks,Lekensteyn撞在了头上。 I didn't fully understand what you were intending to accomplish here... 我不完全了解您打算在这里完成的工作...


That is not exactly a "self-executing function." 那不完全是“自我执行功能”。 If you had built it like this: 如果您是这样构建的:

(function(MyObject) {
    MyObject.alertMessage = "Javascript rules";
    MyObject.ClickHandler = function() {
        alert(this.alertMessage );
    }
})(window.MyObject = window.MyObject || {});

Then I would call it a self-executing function. 然后,我将其称为自执行功能。

Once you've done that, now you could execute MyObject.ClickHandler() and get the alert. 完成此操作后,现在可以执行MyObject.ClickHandler()并获取警报。

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

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