JavaScript “this” references wrong object [duplicate]

给你一囗甜甜゛ 提交于 2019-11-28 11:29:55

You might need to make a tweak like this:

function someObj() {
    var that = this;

    this.someMethod1 = function() {
        var elementBtn = document.getElementById('myBtn');
        elementBtn.onclick = function() { 
            that.someMethod2();
        };
    };
    this.someMethod2 = function() {
       alert('OK');
    };
}

"that" captures the scope you are after.

The function keyword changes scope. One solution is to maintain the reference to the "this" that you want to use.

Try the following:

function someObj() {
   var self = this;
   this.someMethod1 = function() {
      var elementBtn = document.getElementById('myBtn');
      elementBtn.onclick = function() { 
         self.someMethod2(); //NOTE self
      };
   };
   this.someMethod2 = function() {
      alert('OK');
   };
}

You could use coffee script, which has a fat arrow (used for onclick function) to deal with this kind of thing, and compiles to well formed javascript. By using fat arrow, coffee script ensures the same scope as the function is defined in will be used in the callback function.

play with code here

Coffee Script

someObj = () ->
   @someMethod1 = () ->
      elementBtn = document.getElementById 'myBtn'
      elementBtn.onclick = () => 
         @someMethod2()
   this.someMethod2 = () ->
      alert 'OK'

JavaScript

var someObj;
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
someObj = function() {
  this.someMethod1 = function() {
    var elementBtn;
    elementBtn = document.getElementById('myBtn');
    return elementBtn.onclick = __bind(function() {
      return this.someMethod2();
    }, this);
  };
  return this.someMethod2 = function() {
    return alert('OK');
  };
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!