2017-07-03 100 views
0

请看下面的例子:ES6传递一个对象来构造函数,并设置属性

class Parent { 
    constructor({ parentOnlyArg = 'default value' } = {}) { 
     this.parentOnlyArg = parentOnlyArg; 
    } 
} 

class Child extends Parent { 
    // this class and also any class inheriting from it 
    constructor({ visibleStyle = 'inline' } = {}) { 

     // I want to pass argument to super as an object 
     super(/** args **/); 

     this.visibleStyle = visibleStyle; 
    } 
} 

class Child2 extends Parent { 
    // Specifying parentOnlyArg as default will change the behaviour 
    constructor({ parentOnlyArg = 'another parent value', 
        someOther = 'value' } = {}) { 

     // I want to pass argument to super as an object 
     super(/** args **/); 

     this.someOther = someOther; 
    } 
} 

是否有可能通过在构造函数的参数,以超?

好像是比我想象的

super(...arguments); 

简单的话,我可以用

var c1 = new Child(); // c.parentOnlyArg = 'default value' 
var c2 = new Child2(); // c.parentOnlyArg = 'another parent value' 
var c3 = new Child({ parentOnlyArg: 'changed again' }); // c.parentOnlyArg = 'changed again' 
+0

为什么不使用'<>'片段编辑器[MCVE]讯息? – mplungjan

+2

'super({parentOnlyArg})'? – Bergi

+0

任何不将解构结构移入函数体的原因?然后你会得到一个参数来通过变量。 – loganfsmyth

回答

1

一个速赢是使用arguments对象创建Child。它是一个包含传递给函数的所有参数的数组。

有关MDN的更多信息。

实际上,您可以通过arguments[0]访问函数的第一个参数。

class Child extends Parent { 
    constructor({ parentOnlyArg = 'value', 
        visibleStyle = 'inline' } = {}) { 
     super(arguments[0]); 
     [...] 
    } 
} 
+0

虽然这没有错,但这是我如何在一周前做到这一点。缺乏其他选择这将是答案。 – Asken

1

您可以使用object destructuring with rest properties。它尚未被浏览器实现,但BabelJs可以传输它。

function assertEmpty(obj) { 
 
    if (Object.keys(obj).length > 0) { 
 
    throw new Error("Unexpected parameters"); 
 
    } 
 
} 
 
    
 
class A { 
 
    constructor({ a = "foo", ...rest } = {}) { 
 
    assertEmpty(rest); 
 
    console.log("new A " + a); 
 
    } 
 
} 
 
    
 
class B extends A { 
 
    constructor({ b = "bar", ...rest } = {}) { 
 
    super(rest); 
 
    console.log("new B " + b); 
 
    } 
 
} 
 
    
 
new B({a:2}); // prints 'new A 2', 'new B bar' 
 
new B({a:4, b:5, c:6}); // throws 'Unexpected parameters'

在上面的代码中的父类没有看到由后人所消耗的PARAMS。如果您遇到问题,您可以将其作为@Bergi或@loganfsmyth建议。例如:

class A { 
 
    constructor(params = {}) { 
 
    const { a = "foo" } = params; 
 
    console.log("a=" + a); 
 
    } 
 
} 
 

 
class B extends A { 
 
    constructor(params = {}) { 
 
    const { b = "bar" } = params; 
 
    super(params); 
 
    console.log("b=" + b); 
 
    } 
 
} 
 

 
new B({a:2}); // prints a=2 b=bar 
 
new B({b:5}); // prints a=foo b=5

+0

在我刚刚将'... arguments'传递给'super'的更新中,它似乎也能正常工作,并将所有参数传递给父项并保持默认值。您是否看到该解决方案的任何问题? – Asken

+0

唯一的问题可能是性能相关,他们说现代浏览器不能优化访问参数对象的函数。但其他方面没问题。 –

相关问题