在下面的 2 个示例中,new
的工作方式有何不同?我看到第二个示例正在用变量替换讨厌的函数,但在第二个示例中,实际上正在调用函数/类“Person”。被调用与不被调用有什么区别吗?我在没有打电话的情况下尝试过,它仍然有效。所以这让我相信 new 实际上是在调用函数并将 this
设置为分配给实例变量。
var person = new function() {
this.setName = function(name) {
this.name = name;
}
this.sayHi = function() {
return "Hi, my name is " + this.name;
}
}
person.setName("Rafael");
console.log(person.sayHi()); // Hi, my name is Rafael
var Person = function() {
this.setName = function(name) {
this.name = name;
}
this.sayHi = function() {
return "Hi, my name is " + this.name;
}
}
var personTwo = new Person()
personTwo.setName("Rafael");
console.log(personTwo.sayHi()); // Hi, my name is Rafael
最佳答案
如果这是一个像这样的简单函数,那么这两个示例之间几乎没有区别:
(function() { console.log("IIFE"); })();
// or
var f = function() { console.log("Function"); };
f();
您只需将函数存储在变量中,然后调用它即可。
但是,它有一点不同,因为它与 JS OOP 机制有关。在第一种情况下,您获得 Object
实例,在第二种情况下,您获得 Person
实例。这在 OOP 意义上是不同的。
var person = new function() { };
console.log("Is instance of: " + person.constructor.name);
console.log("There is no way to check instanceof in this case");
var Person = function() { };
var person = new Person();
console.log("Is instance of: " + person.constructor.name);
console.log(person instanceof Person);
一般来说,应该像第二种情况一样使用 new
和类,以便启用 JS OOP 的全部功能。使用匿名类构造函数绝对没有任何意义或/和优势。
关于javascript - "new"如何与 javascript 中的类一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40276573/