推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
rupert

一个实例化的问题

  •  
  •   rupert · Oct 30, 2016 · 2312 views
    This topic created in 3510 days ago, the information mentioned may be changed or developed.

    假设有一个这样的构造函数,但是只能得到他的参数个数是不确定的,参数为数组形式 [3,4,5,..], 然后希望实例化出一个对象

    var arr = [3,4,5..]
    function f(a,b..) {
      this.a = a
      this.b = b
      ...
    }
    

    我所知道的方法有两种 new f(...arr)Reflect.construct(f, arr)
    但是我还想知道有没有用 apply 相关解决的方法?

    4 replies    2016-10-30 16:54:48 +08:00
    SoloCompany
        1
    SoloCompany  
       Oct 30, 2016
    或许是 ECMA1 兼容的 Reflect.construct 版本
    function contract(f, arr)
    var x = {}
    x.__proto__ = f.prototype
    f.apply(x, arr)
    return x
    }
    Mutoo
        2
    Mutoo  
       Oct 30, 2016
    var f = function(){
    for(var i=0;i<arguments.length;i++){
    this[String.fromCharCode(97+i)]=arguments[i]
    };
    };

    new f(1,3,4); // Object {a: 1, b: 3, c: 4}
    8qwe24657913
        3
    8qwe24657913  
       Oct 30, 2016 via Android
    new (f.bind.apply(f, [1].concat(arr)))();
    大概这样
    PS ,在没有 bind 的时代人们是这样用的:
    function g(){};
    g.prototype=f.prototype;
    f.apply(new g(),arr);
    但是后来有了 new.target 和 class ,第二种方法不好用了
    如果你用 babel 把 new f(...arr);转成 ES5 的话你会发现用的是第一种方法,只是多个 helper 函数来确保 arr 是个数组而不是什么奇怪的东西
    PPS ,__proto__是浏览器厂商自己搞出来的,说它 ECMA1 兼容的还是要学习一个(逃
    rupert
        4
    rupert  
    OP
       Oct 30, 2016
    @8qwe24657913 赞,正是我想要的, 一楼的解法就是你说的第二种方法吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4182 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 00:56 · PVG 08:56 · LAX 17:56 · JFK 20:56
    ♥ Do have faith in what you're doing.