美团笔试JS小记

419 阅读1分钟

 先上两段代码

(function () {
    var x = y = 1
})()
console.log(x) // x is not defined 报错
console.log(y) // 1

这里其实是变量段作用域问题

x在函数内定义,作用域在函数内,因此外部不能访问

y没有定义,因此默认是全局变量,因此y的值是1

(function () {
    var x = y = 1
    console.log(x, y)
})()
// 1 1

console在函数内可以正确打印x和y的值

下面是第二段

var name = 'a'
var person = {
    name: 'b',
    sayName: function () {
        var name = 'c'
        return this.name
    }
}
person.sayName() // 'b'
var person_1 = person.sayName
person_1() // 'a'

这里其实只要明白this的指向不是定义时确定的,而是执行时确定的。

this指向上一层对象,也就是person

当把person.sayName赋值给变量时,执行函数时,返回this,这时上层对象是全局变量window,因此this.name指向'a'