Javascript新关键字

问题描述 投票:0回答:1

以下列方式创建实例意味着什么?

somevar = new Person.doSomething()

这是创建实例并调用方法的快捷方式,例如

person = new Person ()
person.doSomething()

或者还有其他东西吗?

提前感谢。

javascript new-operator
1个回答
0
投票

否,这不会创建Person的新实例,然后在其上调用一个方法。它创建一个Person.doSomething()的实例。因此,实际上,您这两个是等效的:

const Person = {
  doSomething: function(foo, bar){
    this.foo = foo;
    this.bar = bar;
  }
}

//create a new instance of `Person.doSomething`
const p1 = new Person.doSomething(1, "one");

//take a reference of `Person.doSomething`
const temp = Person.doSomething;
//create an instance of it
const p2 = new temp(2, "two");

console.log("p1:", p1);
console.log("p1 instanceof Person.doSomething:", p1 instanceof Person.doSomething);

console.log("p2:", p2);
console.log("p2 instanceof Person.doSomething:", p2 instanceof Person.doSomething);

您只能使用constructable函数获取实例。这些是普通函数(使用function关键字声明)和class构造函数:

function PlainConstructable(a, b) {
  this.foo = a;
  this.bar = b;
}

const plainInstance = new PlainConstructable("plain", "instance");

class ClassConstructable {
  constructor(a, b) {
    this.foo = a;
    this.bar = b;
  }
}

const classInstance = new ClassConstructable("class", "instance");


console.log(`plainInstance:
  instanceof PlainConstructable: ${plainInstance instanceof PlainConstructable}
  what it holds: ${JSON.stringify(plainInstance)}`);
  
console.log(`classInstance:
  instanceof ClassConstructable: ${classInstance instanceof ClassConstructable}
  what it holds: ${JSON.stringify(classInstance)}`);

不可构造的是:

const arrowFunction = () => {};

const plainObject = {
  shorthandMethod() {}
}

try {
  new arrowFunction();
  console.log("Constructing arrow function successful.");
} catch(e) {
  console.log(
    `Cannot construct arrow function
     ${e}`
   )
}

try {
  new plainObject.shorthandMethod();
  console.log("Constructing shorthand method successful.");
} catch(e) {
  console.log(
    `Cannot construct shorthand method
     ${e}`
   )
}

try {
  new parseInt();
  console.log("Constructing built-in successful.");
} catch(e) {
  console.log(
    `Cannot construct built-in
     ${e}`
   )
}

For more information about constructable functions


0
投票

否,这不会创建Person的新实例,然后在其上调用一个方法。它创建一个Person.doSomething()的实例。因此,实际上,您这两个是等效的:

const Person = {
  doSomething: function(foo, bar){
    this.foo = foo;
    this.bar = bar;
  }
}

//create a new instance of `Person.doSomething`
const p1 = new Person.doSomething(1, "one");

//take a reference of `Person.doSomething`
const temp = Person.doSomething;
//create an instance of it
const p2 = new temp(2, "two");

console.log("p1:", p1);
console.log("p1 instanceof Person.doSomething:", p1 instanceof Person.doSomething);

console.log("p2:", p2);
console.log("p2 instanceof Person.doSomething:", p2 instanceof Person.doSomething);
© www.soinside.com 2019 - 2024. All rights reserved.