关于 this 题目

2018-12-09  本文已影响0人  猫晓封浪

参考文章

  1. fn() 里面的 this 就是 window
  2. fn() 在严格模式下(strict mode), this 是 undefined
  3. a.b.c.fn() 里面的 this 就是 a.b.c (类似 call() 的第一个参数就是 this )
  4. new Fn() 里面的 this 就是新生成的实例
  5. ()=>{} 箭头函数没有 this ,所以里面的 this 根据外边的来

第一题:

window.n = 'window name'
let obj = {
    n: 'obj name',
    sayN(){
        console.log(this.n)
    }
}

let fn = obj.sayN
fn()

这一题输出的是 window namefn 函数在调用时什么都没有传入,此时 this 就是全局的 this

第二题

window.n = 'window name'
let obj = {
    n: 'obj name',
    sayN: () => {
        console.log(this.n)
    }
}

obj.sayN()

这一题考查的是箭头函数的 this 指向问题。箭头函数没有 this ,所以 this 指向根据外边确定。本题中: 外部的 this 指向全局。答案:window name

第三题

class A{
    constructor(){
        this.name = 'A'
    }
    sayName(){
        console.log(this.name)
    }
}
class B extends A{
    constructor(){
        super()
        this.name = 'B'
    }
}

let obj = new B()
console.log(obj.sayName())

本题考查 ES6 中 extend 关键字,继承中的 this 指向问题。此时 B 继承 A 所以 B 有 sayName 方法。答案:B
注意,super 虽然代表了父类 A 的构造函数,但是返回的是子类 B 的实例,即 super 内部的 this 指的是 B,因此 super() 在这里相当于A.prototype.constructor.call(this)

第四题

window.name = 'window name'
let app = new Vue({
    name: 'name 1',
    el: '#app',
    data(){
      return {name:'name 2'}
    },
    created(){
        console.log(this.name)
    }
})

此时, appthis 指向是当前 Vue 实例,并且 name 属性只是一个属性,此时 this.name 指的是当前 data 属性内的 name。答案:name 2

上一篇 下一篇

猜你喜欢

热点阅读