迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 新关键字

作者:迹忆客 最近更新:2024/03/20 浏览次数:

本文帮助你了解 JavaScript 中 new 关键字的用法。


JavaScript 中的 new 关键字是什么

JavaScript 的 new 关键字用于使用构造函数实例化对象。当使用 new 运算符调用构造函数时会发生以下情况。

  1. 生成一个新的空对象。

  2. 新对象的内部 Prototype 属性与构造函数原型相同。

  3. 变量 this 旨在指向新创建的对象。它将用 this 关键字声明的属性绑定到新对象。

  4. 当构造函数返回一个非原始值(自定义 JavaScript 对象)时,返回一个新创建的对象。如果构造函数返回原始值,则忽略它。

    在函数之后,如果函数体中没有返回语句,则返回 this

语法:

new constructorFunction(arguments);

范围:

  1. ConstructorFunction - 指定对象实例类型的类或函数。
  2. 参数 - 将调用构造函数的值列表。

在 JavaScript 中使用 new 关键字

示例 1:

function Book(name, price, pages) {
  this.name = name;
  this.price = price;
  this.pages = pages;
}

const book1 = new Book('Science', 20, 480);

document.write(book1.name);

尝试演示。

输出:

Science

new 关键字在上面的示例中创建了一个空对象。Book() 包括三个属性:namepricepages 通知 this 术语。

结果,一个新的空对象将具有所有这些属性,即名称价格页面。新创建的东西以 book1() 的形式返回。

示例 2:

function func() {
  var as = 1;
  this.s = 500;
}

func.prototype.k = 1000;

var obj = new func();
document.write(obj.s);
document.write('\n');
document.write(obj.k);

尝试演示。

输出:

500 1000

上例中的 new 关键字创建了一个空对象,然后将 prototype 属性设置为 func() 的原型属性。使用 func.prototype.k 分配新属性 k

因此,新实体还将包含 k 属性;然后,它将使用 this 关键字声明的所有属性和函数绑定到一个新的空对象。

这里,func() 只包含一个属性 s,用 this 关键字表示。因此,一个新的开放实体现在将具有 s 属性。

func() 包括 as 变量,未使用 this 关键字声明。因此 as 不会包含在新对象中。

最后,返回新创建的对象。请注意,func() 没有 return 语句。

编译器将在末尾隐式插入 return this

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便