会捕获其所在的上下文的this值,作为自己的this值
call | apply | bind 无法改变箭头函数中this的指向
Generator函数js//函数声明 function test() { } //函数表达式 const test = function () { }
jsfunction Foo() { this.age = 18//实例属性 } Foo.sex = 'women'//静态属性 Foo.sayAge = function () {//静态属性 return 19 } Foo.prototype.sayName = function () {//原型属性 return 'zzf' }
jsclass Bar { static sex = 'women'//静态属性 constructor() { this.age = 18//实例属性 } sayName() { return 'zzf'//原型属性 } sayHello=()=>{ return 'hello'//实例属性 } } Bar.sayAge = function () {//静态属性 return 19 }
babel转译后为
js"use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var Bar = function Bar() { _classCallCheck(this, Bar); _defineProperty(this, "sayName", function () { return 'zzf'; }); this.age = 18; }; _defineProperty(Bar, "sex", 'women'); Bar.sayAge = function () { return 19; };
js
箭头函数的 this 永远指向其上下文的 this ,任何方法都改变不了其指向,如 call() , bind() , apply() ,可以说正是因为没有自己的this,才使其具备了以上介绍的大部分特点; 普通函数的this指向调用它的那个对象
function myNew(fn,...args) {
let obj = {}
obj.__proto__ = fn.prototype
let result = fn.apply(obj,args)
return result instanceof Object ? result : obj
}