箭头函数和普通函数
- 箭头函数不会创建自己的this
会捕获其所在的上下文的this值,作为自己的this值
- 箭头函数继承而来的this指向永远不变
call | apply | bind 无法改变箭头函数中this的指向
- 箭头函数不能作为构造函数使用
- 箭头函数没有自己的arguments
- 箭头函数没有原型prototype
- 不能用做
Generator函数
静态、原型、实例属性
Function
function Foo() {
this.age = 18//实例属性
}
Foo.sex = 'women'//静态属性
Foo.sayAge = function () {//静态属性
return 19
}
Foo.prototype.sayName = function () {//原型属性
return 'zzf'
}
Classs
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;
};
总结
箭头函数的 this 永远指向其上下文的 this ,任何方法都改变不了其指向,如 call() , bind() , apply() ,可以说正是因为没有自己的this,才使其具备了以上介绍的大部分特点; 普通函数的this指向调用它的那个对象
F&Q
new 做了什么
- JS内部首先会先生成一个对象;
- 再把函数中的this指向该对象;
- 然后执行构造函数中的语句;
- 最终返回该对象实例。