对象中的this
let str = `zs`;
const obj = {
str: `ls`,
log(): {
console.log(this.str);
}
}
obj.log();
// ls
在普通函数中,this.str指向了obj对象内的str。而在ES6中新增的箭头函数中又会怎么样呢
let str = `zs`;
const obj = {
str: `ls`,
log: () => {
console.log(this.str);
}
}
obj.log();
// zs
在箭头函数中,this.str指向了外面的str。如果我们在log函数内输出一下this,可以发现this已经指向window了
let str = `zs`;
const obj = {
str: `ls`,
log: () => {
console.log(this);
// console.log(this.str);
}
}
obj.log();
// window
全局下的this
全局调用的this分为严格模式(需要在顶端第一句打 "use strict" 才能开启)和普通模式(也就是平常的时候)。
<script>
//普通模式下
let num = 1;
function fn1() {
console.log(this.num)
};
fn1(); //1
//严格模式下
let num = 1;
function fn1() {
'use strict'
console.log(this.num)
};
fn1(); //undefined
</script>
在普通模式下,全局调用的this指向window,在严格模式中,禁止this指向window所以为undefined。
构造函数中的this
<script>
function Person(str) {
this.str = str;
}
let p1 = new Person('str')
console.log(p1.str); //str
</script>
在构造函数中,this经过new的调用发生了改变,在使用new调用时: 1.new会在内存中新创建一个空对象,且实例化 2.new会让this指向这个新对象 3.new给这个新对象复制属性和方法 4.return这个新对象
4、call,apply调用的this
call和apply函数可以改变普通函数的this指向,但是不能改变箭头函数的this指向。
<script>
let obj1 = {
str: "str",
fn() {
console.log(this.str)
}
}
let obj2 = {
str: "maliao",
fn() {
console.log(this.str)
}
}
obj1.fn.call(obj2) //str2
</script>