【问题标题】:Reflect.construct() Why it is necessary override object prototype?Reflect.construct() 为什么需要覆盖对象原型?
【发布时间】:2016-12-21 20:30:21
【问题描述】:
class Name{
    constructor(name)
    {
      this.name = name
    }
}


function greet()
{
  return "Hello World"
}

let Max = Reflect.construct(Name,["Maxi"],greet);
console.log(Max.__proto__ == greet.prototype); //true 

为什么需要重写对象原型

【问题讨论】:

  • 你能扩展你的问题吗?我觉得你问的不是很清楚。
  • Ok 第一个问题 class Name{ constructor(name) { this.name = name } } let Max = new Name("Maxi") let Max = Reflect.construct(Name,['Maxi'] ) 有什么区别?
  • 你所做的就像var Max = new greet("Maxi"); 就是这样。您只是将greet 函数用作构造函数,并将数组参数(第二个参数)中的值作为参数传递给greet 函数。
  • 为什么要使用它?为什么 Max.__proto__ == greet.prototype 返回 true,我可以在 Max 对象中使用 greet 方法吗?
  • 为了在 Max 对象中使用 greet 方法,您根本不应该摆弄 Reflect 对象。只需执行Name.prototype.greet = n => "Hello" + n; 而不是像那样单独定义greet 函数。然后let Max = new Name("Maxi")

标签: javascript object ecmascript-6


【解决方案1】:

我相信这是你用 ES6 的类实现你想要做的事情的一种方式;

class Name{
    constructor(name)
    {
      this.name = name;
    }
    greet(n){return "Hello " + n;}
}


var Max = new Name("Maxi");
console.log(Max.greet("John"));

【讨论】:

  • 最后一个问题我如何调用 someConstructor 与结果对象函数 someConstructor() { return "hello"; } var result = Reflect.construct(Array, [], someConstructor);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多