提问者:小点点

我可以简化这个构造函数的实例化吗?


有没有可能把下面的代码(特别是new关键字)分解成更简单的代码(这样我就能明白是怎么回事了)?:

null

function F() {
  this.color = 'red';
  this.printNumber = function printNumber() {
    console.log(5);
  };
 }

 let o = new F();
 console.log(o);

null

下面是我的尝试:

当我被告知leto=newf();leto=F.call({})相同时,我以为我是胜利者了,但我可以在控制台看到,第一个还为空对象提供了一个设置为构造函数的constructor属性。

新对象有一个构造函数属性设置为构造函数,这很重要吗? 我知道这个构造函数将被视为一个方法,其中的this将作为一个整体引用这个对象。 这使我认为new的工作原理是:

  1. 立即创建将构造函数属性设置为构造函数函数的对象。
  2. 执行构造函数属性(一个方法),使新对象看起来像:
{
color: "red",
printNumber: printNumber,
constructor: F
//as it is an instance of the inbuilt Object constructor function, it has all the properties/methods of an object
}

共1个答案

匿名用户

新对象有一个构造函数属性设置为构造函数,这很重要吗?

如果您的意图是创建一个可以实例化并从中继承的对象,那么是的,您应该使用new语法。 call()就是这样做的,它调用函数(运行其代码)而不正式实例化对象的实例。 call()还允许您定义当函数运行时此将绑定到什么,但call()new并不相同。

当您使用new实例化时,将创建对象的实例,并执行构造函数。 然后绑定到新实例。

有关new和原型继承如何工作的更多细节,请参阅我的另一篇文章。

另外,供参考的是,您应该向对象的prototype(而不是对象本身)添加对象的方法(无论您有什么特定的实例,这些方法的操作都是相同的):

null

function F() {
  this.color = 'red';
}

// Methods are usually added just once to the object's
// prototype and then all instances inherit it, which
// has a lower memory footprint because the method is
// defined and attached just once instead of on each 
// instance.
F.prototype.printNumber = function printNumber() {
    console.log(5);
};

let o = new F();
console.log(o.color);
o.printNumber();