js the call () methods of use and description

Code Case 1:

window.color = 'red';

document.color = 'blue',

let obj = {
  color : 'pink'
}

function createColor (color){
  this.color = color;
}
let c = new createColor('white');

function showColor(){
  console.log(this.color)
}
showColor() //默认this就是window  red
showColor.call(window) //  red
showColor.call(cocument) //  blue
showColor.call(obj) //  pink
showColor.call(c) //  white

Code Case 2:

var elJson = {
  name:'Web前端',
  callBack:function(){
    console.log(this.name)  
  }
};
var newJson = {
  name:'javaScript is cool'
};

//直接调用
elJson.callBack() //结果是Web前端

//而使用call()方法调用
elJson.callBack.call(newJson ) //结果是javaScript is cool;

Explanation

call () to change the point of this, the beginning point of this is elJson this object, and when using call () this is not the point of this object, but the object of new newJson

Code Case 3:

Use way to construct an object

  var newJson = {
      name:'javaScript is cool'
    };
    function createJs(name){
        this.name = name;
        this.callBack = function(){
            console.log(this.name);
        }
    }
    var cat = new createJs('Web前端');
    cat.callBack(); //结果是Web前端
    cat.callBack.call(newJson) //结果是javaScript is cool;

The principle of the two methods is the same, but this kind of use to construct an object;
in fact, in the js var variables are added to a property in a top-level object window in it

Guess you like

Origin blog.csdn.net/qq_42363090/article/details/93485017