JavaScript function binding (this keyword) is lost after assignment

前端 未结 5 794
甜味超标
甜味超标 2020-11-30 12:28

this is one of most mystery feature in JavaScript, after assigning the object method to other variable, the binding (this keyword) is lost

var john = {
  nam         


        
5条回答
  •  情歌与酒
    2020-11-30 13:35

    Because you're only setting fx to the greet method and not the entire john object, it has no concept of it's parent and becomes globally scoped. So in essence, it's passing by value in that in only copies the method.

    Since the function is now globally scoped, "this" becomes the Window object.

    If you instead set fx to john, you get what's expected.

    var john = {
      name: 'John',
      greet: function(person) {
        alert("Hi " + person + ", my name is " + this.name);
      }
    };
    
    john.greet("Mark"); // Hi Mark, my name is John
    
    var fx = john;  
    fx.greet("Mark"); // Hi Mark, my name is John
    

提交回复
热议问题