this的指向只有在调用时才能被确定,因为this是执行上下文的一部分。
全局作用域中的函数:其内部this指向window
var a = 1;
function fn() {
console. log(this. a)
}
fn() 〃输出1
对象内部的函数:其内部this指向对象本身:
var a = 1;
var obj = {
a: 2,
fn: function() {
console. log (this. a)
}
}
obj.fn() //输出 2

构造函数:其内部this指向生成的实例:
function createP(name,age){
this. name = name //this. name 指向 P
this.age = age //this. age 指向 P
}
var p = new createP ("老李",46)
apply. call. bind改造的函数:其this指向第一个参数:
function add(c,d){
return this. a + this.b + c + d }
var o = {a: 1, b: 2)
add. call (o,5, 7) //输出 15
箭头函数:箭头函数没有自己的this,看其外层的是否有函数,如果有,外层函数的this就 是内部箭头函数的this,如果没有,则this是window。

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.