
在 javascript 中,“new”关键字通过构造函数创建对象的新实例。
新关键字的目的:
对象创建。原型链接。绑定“this”并返回新创建的对象。
运作原理:
当您在构造函数中使用 new 关键字时,将执行以下步骤:
创建了一个新的空对象。新对象的原型设置为构造函数的原型。构造函数被调用到设置了“this”的新对象。如果构造函数没有返回对象,则返回新创建的对象。
例子 :
这是一个简洁的代码示例,演示了 javascript 中 new 关键字的使用,涵盖了对象创建、原型链接和绑定“this”所涉及的所有基本步骤。
// Step 1: Define a constructor functionfunction Car(make, model) { this.make = make; // Step 3: Bind properties to the new object this.model = model;}// Step 4: Add a method to the Car prototypeCar.prototype.getDetails = function() { return `${this.make} ${this.model}`;};// Step 2: Create a new instance of Car using the new keywordconst myCar = new Car('Toyota', 'Corolla');// Using the method from the prototypeconsole.log(myCar.getDetails()); // Output: Toyota Corolla// To demonstrate the prototype linkageconsole.log(myCar instanceof Car); // Output: true
概括
综上所述,new 关键字对于 javascript 中的面向对象编程至关重要。它允许创建对象的新实例,建立原型继承,绑定 this 的上下文,并处理创建的对象的返回。了解 new 的工作原理对于在 javascript 中有效使用构造函数和类至关重要。
以上就是&#新&#关键字的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1498972.html
微信扫一扫
支付宝扫一扫