this关键字如何用于函数表达式和箭头函数?

时间:2017-07-17 09:04:40

标签: javascript html this arrow-functions

最近我一直在阅读“JavaScript忍者的秘密”#39;通过John Resig和我已经达到列表4.10,即#34;将一个特定的上下文绑定到一个函数"单击按钮时代码打印的位置。 作者表明,只有使用箭头函数而不是正常的函数表达式,代码才能成功运行。为什么代码在函数表达式中运行良好?以及关键字如何运作?

以下是包含函数表达式的代码:



function Button() {
  this.clicked = false;
  this.click = function() {
    this.clicked = true;
    if (button.clicked) {
      "The button has been clicked"
    };
  };
}
var button = new Button();
var elem = document.getElementById("test");
elem.addEventListener("click", button.click);

<button id="test">Click Me!</button>
&#13;
&#13;
&#13;

以及带箭头功能的代码(完美无瑕):

&#13;
&#13;
function Button() {
  this.clicked = false;
  this.click = () => {
    this.clicked = true;
    if (button.clicked) {
      console.log("The button has been clicked");
    }
  };
}
var button = new Button();
var elem = document.getElementById("test");
elem.addEventListener("click", button.click);
&#13;
<button id="test">Click Me!</button>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您可以运行以下代码。

function Button1() {
  this.clicked = false;
  this.click = function() {
    this.clicked = true;
	console.log('bt1',this);
    if (button1.clicked) {
      console.log("The button has been clicked 1");	
    };
  };
}
function Button2() {
  this.clicked = false;
  this.click = () => {
    this.clicked = true;
	console.log('bt2',this);
    if (button2.clicked) {
      console.log("The button has been clicked 2");
    }
  };
}

var button1 = new Button1();
var button2 = new Button2();
var elem = document.getElementById("test");
elem.addEventListener("click", button1.click);
elem.addEventListener("click", button2.click);
<button id="test">Click Me!</button>

'this'只是正常功能中的HTML。

如果yuo使用'button1.click.bind(button1)',将成功运行。