zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    SPOJ ADAFIELD Ada and Field(STL的使用:set,multiset,map的迭代器)题解
    hdu 6444 网络赛 Neko's loop(单调队列 + 裴蜀定理)题解
    hdu6446 网络赛 Tree and Permutation(树形dp求任意两点距离之和)题解
    HDU6447 网络赛 YJJ's Salesman(DP + 线段树)题解
    HDU 6438 网络赛 Buy and Resell(贪心 + 优先队列)题解
    BZOJ 3155 Preprefix sum
    BZOJ 2743 采花
    BZOJ 3339 Rmq Problem
    BZOJ 1660 乱发节
    BZOJ 3531 旅行
  • 原文地址:https://www.cnblogs.com/WindrunnerMax/p/12565172.html
Copyright © 2011-2022 走看看