javasript中的this
javascript中的this不像java里面的this明确,以下作了一些测试,为了让自己区分在不同情况下javasript中的this指代的是哪一个对象。
// var x = 6
// 类
class ClassTest {
constructor(x) {
this.x = x // 这里的this指类对象,代码含义是在类对象中添加变量x,创建对象时给x赋值
}
test(y) {
this.y = y // 类方法里面的的this同样指类对象(构造方法是特殊的方法)
}
}
// 函数
function funTest(x) {
this.x = x // 这里的this指全局对象,代码含义是添加一个全局变量x
}
// 对象
var point = {
x: 0,
add: function add() {
this.x = this.x+1 // point对象方法中的this指point对象
}
}
// funTest(4)
// var test = new ClassTest(6)
// test.test(9)
// console.log(point.x)
// point.add()
console.log(point.x)

浙公网安备 33010602011771号