Js中this指向问题(函数的调用方式)

在ES6之前,函数内部的this是由函数的调用方式决定的

 

 

函数调用

 

var age = 18;
var p ={
	age : 15,
	say : function(){
		console.log(this.age)
        }
}
var f1 = p.say;
f1();

这时是函数调用(是由window调用,即f1() = window.f1())。 

此时结果为18,因为this指向window。

 

方法调用

 

var age = 18;
var p ={
	age : 15,
	say : function(){
	  onsole.log(this.age)
        }
}
p.say();
 

 

方法调用,结果为15,这里的this指向p对象。  

 

new调用(构造函数)

 

var age=18;
var p={
        age : 15,
        say : function(){
            console.log(this.age);
        }
}
new p.say()
 

 

构造函数调用 ,这时 p.say 属于Object,为Object的实例。

this:say构造函数的实例,实例中并没有age属性,值为:undefined  

佛山vi设计https://www.houdianzi.com/fsvi/ 豌豆资源搜索大全https://55wd.com

上下文方式(call、apply、bind)

 

    function f1(){
        console.log(this);
    }
    
  //  call方法的第一个参数决定了函数内部的this的值
    f1.call([1,3,5])
    f1.call({age:20,height:1000})
    f1.call(1)      
    f1.call("abc")
    f1.call(true);
    f1.call(null)
    f1.call(undefined);

上述代码可以用apply完全替换

var obj = {
	name: "西瓜",
	eat: function() {
		setInterval(function() {
			console.log(this.name);
		}, 100);
	},
	hava: function() {
		setInterval((function() {
			console.log(this.name);
		}).bind(this), 100);
	},
	small: function() {
		setInterval(() => {
			console.log(this.name);
		}, 100);
	}
};

 

总结:

 call方法的第一个参数: 

1、如果是一个对象类型,那么函数内部的this指向该对象 

2、如果是undefined、null,那么函数内部的this指向window 

3、如果是数字-->this:对应的Number构造函数的实例 -- > 1 -- > new Number(1) 如果是字符串-- >this:String构造函数的实例 -- > "abc" -- > new String("abc") 如果是布尔值-- >this:Boolean构造函数的实例 -- > false -- > new Boolean(false) 

在示例 2 中,依次为undefined, 西瓜,西瓜(ES6中箭头函数)。

posted @ 2020-10-22 17:32  酷儿q  阅读(390)  评论(0)    收藏  举报