从 Mozilla 文档中,我通过以下链接了解了 new 运算符: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const car1 = new Car('Eagle', 'Talon TSi', 1993);
console.log(car1.make);
// expected output: "Eagle"
Run Code Online (Sandbox Code Playgroud)
但我也可以在不使用“this”和“new”运算符的情况下执行此操作:
var Car = (make, model, year) => ({make, model, year})
var car1 = Car('Eagle', 'Talon TSi', 1993)
console.log(car1.make)
Run Code Online (Sandbox Code Playgroud)
如果我可以在不使用“this”和“new”运算符的情况下实现相同的结果,那么首先使用它们的意义何在?或者我错过了什么重要的事情?谢谢。我对菜鸟问题感到抱歉。
小智 1
You have the same doubt that most beginners have, the class declaration by function and instantiation, and a function returning an object are very different.
function ClassName(params) {
this.params = params;
}
Run Code Online (Sandbox Code Playgroud)
This creates a class with the name ClassName and saying new ClassName returns an instance of the class ClassName, but the other thing you wrote is:
var ClassName = (params) => ({params: params});
Run Code Online (Sandbox Code Playgroud)
What this means is that it creates a function and sets its return value to the object containing the params.
Pros and Cons:
第一种方法:
优点:你可以很容易地看到一个对象是另一个对象(特别是一个类)的实例ClassInstance instanceof CLassName,在你的例子中,car1 instanceof Car它返回一个布尔
值缺点:(到目前为止,我没有得到任何缺点此方法,如果您对此方法有任何缺点,请评论,我会考虑它们)
第二种方法:
优点:每个创建的对象都是自己的,与由同一函数创建的相同外观的其他对象没有关系(我不知道这有什么帮助,但在某些情况下,它可能会有所帮助)
缺点:你不能通过使用检查对象是否相同(或同一父对象的实例)ClassInstance instanceof Class,它只会返回 false,而且它不会创建实例,它只会创建一个对象
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |