全局上下文:
不论是否在严格模式下,在全局执行环境中
this都指向window
一般函数上下文:
this的值在调用时决定
非严格模式:未设置this,this会指向window,
严格模式:未设置this,this会保持undefined
对象的方法:
当函数作为对象里的方法被调用时,this被设置为调用该函数的对象
类中的方法:
方法中的this依旧取决于调用,可以被改写,在类的constructor中使用bind绑定方法的this
箭头函数的this:
箭头函数没有单独的this,它只会从自己作用域链的上一层继承this
在箭头函数里,严格模式中与this相关的规则都将被忽略
派生类:
派生类构造函数没有初始的this,在构造函数中调用super()时会生成一个this的绑定
警告:在调用super()之前引用this会报错
bind方法绑定this:
bind方法得到的新函数,将无法再次使用bind,因为this已经被永久的与调用时的第一个参数绑定在一起了,
不管这个新函数如何被调用
原型链方法:
对象原型链某处定义的方法,里面的this指向调用这个方法的对象
构造函数:
this和对象的转换:
在非严格模式下使用 call和 apply时,如果用作this的值不是对象,则会被尝试转换为对象。
null和 undefined被转换为全局对象。
如原始值 7 或 ‘foo’会使用相应的构造函数转为对象
例题:
window.n = 'window name'let obj = {n: 'obj name',sayN(){console.log(this.n)},sayN2: ()=>{console.log(this.n)}}let fn = obj.sayNfn()//一般函数,调用时并未设置,所以this指向windowobj.sayN()//对象方法,this指向该对象obj.sayN2()//箭头函数,this取决于它作用域链上一层的this
class A{constructor(){this.name = 'A'console.log(this)}sayName(){console.log(this.name)}}class B extends A{constructor(){super()this.name = 'B'console.log(this)}}let objA = new A()console.log(objA.sayName())//this指向类的实例let objB = new B()console.log(objB.sayName())
var myMixin = {created: function () {this.hello()},methods: {hello: function () {console.log('hello from mixin!')}}}var Component = Vue.extend({mixins: [myMixin],methods: {hello(){console.log('hello from options')}}})var component = new Component()//输出'hello from options'
