箭头函数和普通函数
- 箭头函数不会创建自己的this
会捕获其所在的上下文的this值,作为自己的this值
- 箭头函数继承而来的this指向永远不变
call | apply | bind 无法改变箭头函数中this的指向
- 箭头函数不能作为构造函数使用
- 箭头函数没有自己的arguments
- 箭头函数没有原型prototype
- 不能用做
Generator
函数
函数声明和函数表达式
//函数声明
function test() {
}
//函数表达式
const test = function () {
}
- 函数声明提升
静态、原型、实例属性
Function
function Foo() {
this.age = 18//实例属性
}
Foo.sex = 'women'//静态属性
Foo.sayAge = function () {//静态属性
return 19
}
Foo.prototype.sayName = function () {//原型属性
return 'zzf'
}
Class
class Bar {
static sex = 'women'//静态属性
constructor() {
this.age = 18//实例属性
}
sayName() {
return 'zzf'//原型属性
}
sayHello=()=>{
return 'hello'//实例属性
}
}
Bar.sayAge = function () {//静态属性
return 19
}
babel转译后为
"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;
};
new过程
- 创建一个空的简单Javascript对象 (即{})
- 继承父类原型上的方法
- 添加父类的属性到新的对象上并初始化. 保存方法的执行结果
- 如果执行结果有返回值并且是一个对象, 返回执行的结果, 否则, 返回新创建的对象
function myNew(fn,...args) {
let obj = {}
obj.__proto__ = fn.prototype
let result = fn.apply(obj,args)
return result instanceof Object ? result : obj
}
总结
箭头函数的 this 永远指向其上下文的 this ,任何方法都改变不了其指向,如 call() , bind() , apply() ,可以说正是因为没有自己的this,才使其具备了以上介绍的大部分特点; 普通函数的this指向调用它的那个对象