js new运算符
时间: 2023-07-08 21:09:51 浏览: 42
`new` 运算符是 JavaScript 中用于创建新对象的运算符。通过 `new` 运算符,我们可以实例化一个构造函数,从而创建一个新的对象。
使用 `new` 运算符创建对象的步骤如下:
1. 创建一个空对象。
2. 将这个空对象的 `__proto__` 属性指向构造函数的原型对象。
3. 执行构造函数,并将 `this` 绑定到这个空对象上。
4. 如果构造函数返回一个对象,则返回这个对象,否则返回创建的空对象。
例如,我们可以使用以下代码创建一个 `Person` 对象:
```javascript
function Person(name, age) {
this.name = name;
this.age = age;
}
let person = new Person('Tom', 20);
console.log(person.name); // "Tom"
console.log(person.age); // 20
```
在这个例子中,我们定义了一个 `Person` 构造函数,它接受 `name` 和 `age` 两个参数,并将它们分别赋值给 `this.name` 和 `this.age`。然后,我们使用 `new` 运算符创建了一个新的 `Person` 对象,并将其赋值给变量 `person`。最后,我们可以通过 `person.name` 和 `person.age` 访问该对象的属性。
相关问题
JS模拟的new运算符工作原理(new运算符的伪码实现)
当我们使用 `new` 运算符创建一个对象时,实际上发生了以下几个步骤:
1. 创建一个新对象;
2. 将这个新对象的原型(`__proto__`)指向构造函数(`constructor`)的原型对象(`prototype`);
3. 将构造函数(`constructor`)的`this`指向这个新对象;
4. 执行构造函数(`constructor`)中的代码;
5. 返回这个新对象。
下面是一个 `new` 运算符的伪码实现:
```javascript
function myNew(constructor, ...args) {
// 1. 创建一个新对象
const obj = {};
// 2. 将新对象的原型指向构造函数的原型对象
obj.__proto__ = constructor.prototype;
// 3. 将构造函数的 this 指向新对象
const result = constructor.apply(obj, args);
// 4. 如果构造函数返回的是一个对象,则返回这个对象;否则返回新对象
return typeof result === 'object' ? result : obj;
}
```
使用这个 `myNew` 函数可以模拟 `new` 运算符的行为,例如:
```javascript
function Person(name, age) {
this.name = name;
this.age = age;
}
const person = myNew(Person, 'John', 30);
console.log(person); // { name: 'John', age: 30 }
console.log(person instanceof Person); // true
```
new运算符动态建立矩形对象r1
Sorry, as an AI language model, I am not able to execute code or create objects in real-time. However, here's an example of how you can dynamically create a rectangle object using the `new` operator in JavaScript:
```
// Define a Rectangle class
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
}
// Create a new rectangle object dynamically
const r1 = new Rectangle(10, 20);
console.log(r1.area); // Output: 200
```
In this example, we define a `Rectangle` class with a constructor that takes `width` and `height` as parameters. We also define a `get` accessor for the `area` property, which calculates the area of the rectangle.
Then, we use the `new` operator to create a new `Rectangle` object with the `width` of 10 and `height` of 20, and assign it to the variable `r1`. Finally, we log the area of `r1` to the console, which outputs `200`.