JavaScript 新关键字
本文帮助你了解 JavaScript 中 new
关键字的用法。
JavaScript 中的 new
关键字是什么
JavaScript 的 new
关键字用于使用构造函数实例化对象。当使用 new
运算符调用构造函数时会发生以下情况。
-
生成一个新的空对象。
-
新对象的内部
Prototype
属性与构造函数原型相同。 -
变量
this
旨在指向新创建的对象。它将用this
关键字声明的属性绑定到新对象。 -
当构造函数返回一个非原始值(自定义 JavaScript 对象)时,返回一个新创建的对象。如果构造函数返回原始值,则忽略它。
在函数之后,如果函数体中没有返回语句,则返回
this
。
语法:
new constructorFunction(arguments);
范围:
ConstructorFunction
- 指定对象实例类型的类或函数。参数
- 将调用构造函数的值列表。
在 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()
包括三个属性:name
、price
和 pages
通知 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
。
相关文章
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 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。