函数中的this - js基础深入
this是什么?
-
任何函数本质上是通过某个对象调用,如果没有直接指定就是window
-
所有函数内部都有一个变量this
-
this值是调用该函数的对象
如何确定this的值?
-
test(): window
-
p.test(): p
-
new test(): 新创建的对象
-
p.call(obj): obj
function Person (color) {
console.log(this)
this.color = color
this.getColor = function () {
console.log(this)
return this.color
};
this.setColor = function (color) {
console.log(this)
this.color = color
};
}
Person("red"); // this = window
var p = new Person("yellow"); // this = p
p.getColor() // this = p
var obj = ()
p.setColor.call(obj, "black") // this = obj
var test = p.setColor
test() // this = window
function fn1 () {
function fn2 () {
console.log(this)
}
fn2 () // this = window
}
fn1()