如何构造一个对象并将结果作为参数传递给类构造函数?

时间:2018-02-06 23:10:54

标签: javascript ecmascript-6

class Cat {
  constructor(words, feet) {
    //this.meow(words);
    this.words = words;
    this.feet = feet;
  }
  meow() {
    console.log(`meow${this.words}${this.feet}`);
  }
}

class Tiger {
  constructor(words) {
    this.words = words;
    //this.rowr(words);
  }
  rowr() {
    console.log(`rowr${this.words}`);
  }
}
const param = {
  words: 'abc',
  feet: 2,
}
const cat = new Cat(...param);
console.log(cat.meow())

我得到了meowundefinedundefined

为什么?请注意,我启用了es6 babel。

3 个答案:

答案 0 :(得分:3)

您正在尝试将对象传播到参数中。您只能将对象传播到另一个对象。要构造它,请在构造函数定义中使用花括号。

注意:对象rest/spread仍为stage 3 proposal,需要babel transform才能正常工作。



class Cat {
  constructor({ words, feet }) { // destructure the object
    //this.meow(words);
    this.words = words;
    this.feet = feet;
  }
  meow() {
    console.log(`meow${this.words}${this.feet}`);
  }
}

class Tiger {
  constructor(words) {
    this.words = words;
    //this.rowr(words);
  }
  rowr() {
    console.log(`rowr${this.words}`);
  }
}
const param = {
  words: 'abc',
  feet: 2,
}
const cat = new Cat(param);
cat.meow() // meow doesn't return anything, so console.log it will give you undefined




另一种选择是在外部对其进行解构,然后将其分配给构造函数:



class Cat {
  constructor(words, feet) {
    //this.meow(words);
    this.words = words;
    this.feet = feet;
  }
  meow() {
    console.log(`meow${this.words}${this.feet}`);
  }
}

class Tiger {
  constructor(words) {
    this.words = words;
    //this.rowr(words);
  }
  rowr() {
    console.log(`rowr${this.words}`);
  }
}
const { words, feet } = {
  words: 'abc',
  feet: 2,
}
const cat = new Cat(words, feet);
cat.meow() // meow doesn't return anything, so console.log it will give you undefined




答案 1 :(得分:1)

你无法对这样的对象进行解构来填充方法的参数。您应该尝试解构数组以传递给构造函数或更改构造函数以接收对象。单词和双脚是不确定的,因为它们永远不会像你期望的那样传递给结构。

class Cat {
  constructor(words, feet) {
    //this.meow(words);
    this.words = words;
    this.feet = feet;
  }
  meow() {
    console.log(`meow${this.words}${this.feet}`);
  }
}

class Tiger {
  constructor(words) {
    this.words = words;
    //this.rowr(words);
  }
  rowr() {
    console.log(`rowr${this.words}`);
  }
}

const p = ['abc', 2];
const icat = new Cat(...p); //right
icat.meow(); // meowabc2

结帐this codepen

答案 2 :(得分:0)

尝试传播数组项。 E.g:

const words = 'abc';
const feet = 2;
const param = [
    words,
    feet
];