Js的new运算符

时间:2022-07-24
本文章向大家介绍Js的new运算符,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

new运算符

JavaScript中,new是一个语法糖,可以简化代码的编写,可以批量创建对象实例。 语法糖Syntactic sugar,指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。通常来说使用语法糖能够增加程序的可读性,从而减少程序代码出错的机会。

实例

假如我们不使用new,来初始化创建10个student对象实例

var stuGroup = [];
for(let i=0;i<10;++i){
    var obj = {
        name: i,
        hp: 100,
        mp: 1000,
        power: 100,
        defense: 100
    }
    stuGroup.push(obj);
}
console.log(stuGroup);

此时得到了10个初始化的student对象实例,假如使用new关键字可以简化操作,还可以使用原型链来共享属性等操作。

function Student(i){
    this.name = i;
    this.hp = 100;
    this.mp = 1000;
    this.power = 100,
    this.defense = 100;
}
Student.prototype.from = "sdust";
var stuGroup = [];
for(let i=0;i<10;++i){
    stuGroup.push(new Student(i));
}
console.log(stuGroup);

new运算符的操作

  1. 创建一个空的简单JavaScript对象(即{})
  2. 链接该对象(即设置该对象的构造函数)到另一个对象
  3. 将步骤1新创建的对象作为this的上下文
  4. 如果该函数没有返回对象,则返回this
function _new(base,...args){
    var obj = {};
    obj.__proto__ = base.prototype;
    base.apply(obj,args);
    return obj;
}
function Student(i){
    this.name = i;
    this.hp = 100;
    this.mp = 1000;
    this.power = 100,
    this.defense = 100;
}
Student.prototype.from = "sdust";
var stuGroup = [];
for(let i=0;i<10;++i){
    stuGroup.push(_new(Student,i));
}
console.log(stuGroup);

相关

原型与原型链
https://github.com/WindrunnerMax/EveryDay/blob/master/JavaScript/%E5%8E%9F%E5%9E%8B%E4%B8%8E%E5%8E%9F%E5%9E%8B%E9%93%BE.md
apply、call、bind
https://github.com/WindrunnerMax/EveryDay/blob/master/JavaScript/apply%E3%80%81call%E3%80%81bind.md