专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

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

文章永久链接:https://tech.souyunku.com/39546

未经允许不得转载:搜云库技术团队 » Js的new运算符

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们