fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

箭头函数,为什么不能通过new生成实例?

Open habc0807 opened this issue 4 years ago • 4 comments

habc0807 avatar Aug 04 '20 01:08 habc0807

new关键字被用来创建一个实例。

new 在执行过程中,会进行以下4个操作

  • 创建一个空的简单JavaScript对象(即{});
  • 链接该对象(即设置该对象的构造函数)到另一个对象 ;
  • 将步骤1新创建的对象作为this的上下文 ;
  • 如果该函数没有返回对象,则返回this。

箭头函数本身没有this指向,所以 new 无法执行操作。

Casseil-1996 avatar Aug 04 '20 01:08 Casseil-1996

没有对象原型属性

jianghr-rr avatar Aug 04 '20 02:08 jianghr-rr

new 的本质是生成一个新对象,将对象的_proto_指向函数的prototype,再执行call 方法 普通构造函数通过 new 实例化对象时 this 指向实例对象,而箭头函数没有自己的this值,用call()或者apply()调用箭头函数时,无法对this进行绑定 箭头函数没有 prototype 属性 ,不能作为构造函数,否则 new 命令在执行时无法将构造函数的 prototype 赋值给 新的对象的 proto

AMY-Y avatar Aug 04 '20 02:08 AMY-Y

首先我们需要知道如何 new 出来一个实例(对象类型的实例或者构造函数的实例)

new关键字 会进行如下的操作:

    1. 创建一个空的简单JavaScript对象;
    1. 链接该对象到另一个对象;
    1. 将步骤1新创建的对象作为this的上下文;
    1. 如果该函数没有返回对象,则返回this。

手动实现一个New函数

function New(fc) {
    let newObj = {}
    if(fc.prototype !== null) {
        newObj.__proto__ = fc.prototype
    }

    let res = fc.apply(newObj, Array.prototype.slice.call(arguments, 1))
    // console.log(res)
    if((typeof res === 'object' || typeof res === 'function') && res !== null) {
        return res 
    }

    return newObj
}


function A(){
    return 1
}

console.log(New(A))
// 等价于
console.log(new A())

箭头函数没有自己的this和原型属性,所以箭头函数不能执行 new 操作。

habc0807 avatar Aug 04 '20 06:08 habc0807