您的位置:首页 > Web前端 > JavaScript

JavaScript学习笔记 ------ this指向和箭头函数的作用

2019-02-21 22:23 831 查看

一般的三种情况的this指向

 第一种: 没有创建对象,谁(对象)调用的方法中的this指向谁

function fun(){
console.log(this  === window);
}
//this == window  (仅限于浏览器中运行,使用nodejs运行则不同)
fun(); //true

 第二种:通过构造函数创建对象,this指向该对象

let name = "张三";

function Person( name, age, sex){
this.name = name;
this.age = age;
this.sex = sex;
this.getName = function(){
console.log("name:" + this.name);
//console.log("name:" + name);  结果为:张三
};
this.getAge = function(){......}
this.getSex = function(){......}
}

let xm = new Person("小明", 12, 男);

xm.getName();
//输出结果为:小明
//---其实和第一种一样,这里是通过xm这个对象掉用的name,所以name指向xm这个对象---

 第三中:直接创建对象,this指向该对象

let color = "black";

let cat = {
color : "white",
age : 3
getName : function(){
console.log(this.color);
//console.log(color)  输出为:black
}
}

//结果为: white
//和第二中情况是一样的概念
cat.getName();

以上三种情况都是是一种概念,就是哪个对象调用的方法,方法中的this就指向哪个对象,掉对象自身的属性和方法必须通过他this掉用,否者会根据作用域来寻找变量

箭头函数

 使用箭头函数

function Person(){
let that = this;
this.mSet = function(){
setInterval(() => {
console.log(this === window);  //false
//console.log(this === that);  //true
}, 2000)
}
}

let xm = new Person();

 不使用箭头函数

function Person(){
let that = this;
this.mSet = function(){
setInterval( function() {
console.log(this === window);  //true
//console.log(this === that);  //false
}, 2000)
}
}

let xm = new Person();

可以理解为:使用箭头函数不会绑定this(不会谁掉用this就指向谁),而是指向当前对象

- 学习笔记,仅供参考

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: