一、原型链
- 构造函数Person 通过prototype属性指向实例原型;实例原型也是一个对象,对象都有属性__proto__,实例原型通过__proto__外面的contructor指向构造函数Person。
- 构造函数Person实例person,为一个对象,通过__proto__指向实例原型
- 原型链为 实例person通过__proto__指向实例原型Person.prototype,实例原型通过__proto__指向实例原型的原型,......,最终指向根原型Object.prototype(因为Object.prototype的原型为null)
二、一般函数与箭头函数
1、区别
箭头函数是匿名函数,不能作为构造函数,不能应用new
let FunConstructor = () => { console.log('lll');}let fc = new FunConstructor();
箭头函数不绑定arguments,取而代之用rest参数...解决
function A(a){ console.log(arguments);}A(1,2,3,4,5,8); // [1, 2, 3, 4, 5, 8, callee: ƒ, Symbol(Symbol.iterator): ƒ]let B = (b)=>{ console.log(arguments);}B(2,92,32,32); // Uncaught ReferenceError: arguments is not definedlet C = (...c) => { console.log(c);}C(3,82,32,11323); // [3, 82, 32, 11323]
箭头函数不绑定this,会捕捉其所在的上下文的this值,作为本人的this值
var obj = { a: 10, b: () => { console.log(this.a); // undefined console.log(this); // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …} }, c: function() { console.log(this.a); // 10 console.log(this); // {a: 10, b: ƒ, c: ƒ} }}obj.b(); obj.c();var obj = { a: 10, b: function(){ console.log(this.a); //10 }, c: function() { return ()=>{ console.log(this.a); //10 } }}obj.b(); obj.c()();
箭头函数通过 call() 或 apply() 办法调用一个函数时,只传入了一个参数,对 this 并没有影响。
let obj2 = { a: 10, b: function(n) { let f = (n) => n + this.a; return f(n); }, c: function(n) { let f = (n) => n + this.a; let m = { a: 20 }; return f.call(m,n); }};console.log(obj2.b(1)); // 11console.log(obj2.c(1)); // 11
箭头函数没有原型属性
var a = ()=>{ return 1;}function b(){ return 2;}console.log(a.prototype); // undefinedconsole.log(b.prototype); // {constructor: ƒ}
箭头函数不能当做Generator函数,不能应用yield关键字
2、JS this指向问题
一般函数的this的指向在函数定义的时候是确定不了的,只有函数执行的时候能力确定this到底指向谁,实际上this的最终指向的是那个调用它的对象。
箭头函数比拟非凡没有调用者,不存在this.箭头函数()的概念,然而它外部能够有this,而外部的this由上下文决定
例子1:
var o = { user:"追梦子", fn:function(){ console.log(this.user); //追梦子 }}o.fn();
这里的this指向的是对象o,因为你调用这个fn是通过o.fn()执行的,那天然指向就是对象o。
例子2:
var o = { a:10, b:{ // a:12, fn:function(){ console.log(this.a); //undefined } }}o.b.fn();
只管对象b中没有属性a,这个this指向的也是对象b,因为this只会指向它的上一级对象,不论这个对象中有没有this要的货色。
例子3:
var o = { a:10, b:{ a:12, fn:function(){ console.log(this.a); //undefined console.log(this); //window } }}var j = o.b.fn;j();
这里this指向的是window,this永远指向的是最初调用它的对象,也就是看它执行的时候是谁调用的。
function fn(){ this.num = 1;}var a = new fn();console.log(a.num); //1
为什么this会指向a?首先new关键字会创立一个空的对象,而后会主动调用一个函数apply办法,将this指向这个空对象,这样的话函数外部的this就会被这个空的对象代替。
注: 1 .在严格版中的默认的this不再是window,而是undefined。
2. new操作符会扭转函数this的指向问题。