this指向和new关键字

this指向

1. 默认绑定
function girl1() {
  console.log(this) // window
}
girl1()

2. 隐式绑定

var girl2 = {
  name: '小红',
  age: 18,
  detail: function () {
    console.log(this) // 指向 girl2 对象
    console.log('姓名: ', this.name)
    console.log('年级: ', this.age)
  }
}
girl2.detail()

3. 硬绑定

var girlName = {
  name: '小红',
  sanName: function () {
    console.log(this) // 指向 call,apply 的对象
    console.log('我的女孩:', this.name)
  }
}
var girl3 = {
  name: '小白'
}
var girl4 = {
  name: '小黄'
}
girlName.sanName.call(girl3)
girlName.sanName.call(girl4)

4. 构造函数绑定

function Lover(name) {
  this.name = name
  this.sayName = function () {
    console.log(this) // 指向调用构造函数生成的实例
    console.log('我的女孩:', this.name)
  }
}
var name = '小白'
var xiaoHong = new Lover('小红')
xiaoHong.sayName()
例题1:
function a() {
  function b() {
    console.log(this) // window
    function c() {
      'use strict'
      console.log(this) // undefined
    }
    c()
  }
  b()
}
a()

例题2:

var name = '小白'
function special() {
  console.log('姓名: ', this.name)
}
var girl = {
  name: '小红',
  detail: function () {
    console.log('姓名: ', this.name)
  },
  woman: {
    name: '小黄',
    detail: function () {
      console.log('姓名: ', this.name)
    }
  },
  special: special
}
girl.detail() // 小红
girl.woman.detail() // 小黄
girl.special() // 小红

例题3:

var name = '小红'
function a() {
  var name = '小白'
  console.log('姓名: ', this.name)
}
function d(i) {
  return i()
}
var b = {
  name: '小黄',
  detail: function () {
    console.log('姓名: ', this.name)
  },
  bibi: function () {
    return function () {
      console.log('姓名: ', this.name)
    }
  }
}

var c = b.detail // 此时变量 c 和 b.detail ,没什么关系了
b.a = a
var e = b.bibi()
a() // 全局调用,发生默认绑定 =》 小红
c() // 隐式绑定  小红
b.a() // 小黄 动作被用到 b 里面
d(b.detail) // 小红 调用 d
e() // 小红

new 一个对象的过程

function Father(firstName) {
  this.firstName = firstName
}
var son = Father('李')
 
1. 创建一个新对象`son`
2. 新对象会被执行`[[prototype]]`连接: `son.__proto__ = Father.prototype`
3. 新对象和函数调用的`this`会绑定起来: `Father.call(son, '李')`
4. 执行构造函数中的代码:`this.firstName = firstName`
5. 如果函数没有返回值,那么就会自动返回这个新对象。 `return this`
 
原文地址:https://www.cnblogs.com/houfee/p/14281913.html