如何将两个/多个对象作为参数传递给函数

时间:2016-08-07 05:38:21

标签: javascript

我能够得到第一个参数iAmDogthis也可以访问第一个参数,如何传递第二个参数iAmCat并打印出来?

var speak = function(iAmDog, iAmCat) {
  console.log(this);

  console.log(iAmDog.love);
  console.log(iAmDog.normal);

  console.log(iAmCat.love);
  console.log(iAmCat.normal);
};

var speakAsDog = {
  normal: "moof",
  love: 'woow'
};
var speakAsCat = {
  normal: "meow",
  love: 'purr'
};

speak.call(speakAsDog, speakAsCat);

3 个答案:

答案 0 :(得分:2)

你的代码只是错综复杂的错别字。此外,您不必显式调用.call()函数。

var speak = function (iAmDog, iAmCat) {
  console.log(iAmDog.love);
  console.log(iAmDog.normal);

  console.log(iAmCat.love);
  console.log(iAmCat.normal);
};

var speakAsDog = { normal: "moof", love: 'woow' };
var speakAsCat = { normal: "meow", love: 'purr' };

speak(speakAsDog, speakAsCat);

答案 1 :(得分:0)

function.callfunction.apply中的第一个参数是thisArg,它在函数内可用作this值。因此,如果你想传递任何参数,你应该从第二个开始。在你的情况下,你可以发送null作为thisArg,因为这不会在函数内部引用。

var speak = function(iAmDog, iAmCat) {
  console.log(iAmDog.love);
  console.log(iAmDog.normal);

  console.log(iAmCat.love);
  console.log(iAmCat.normal);
};

var speakAsDog = { normal: "moof", love: 'woow' };
var speakAsCat = { normal: "meow", love: 'purr' };

speak.call(null, speakAsDog, speakAsCat);
speak.apply(null, [speakAsDog, speakAsCat]);

答案 2 :(得分:-1)

根据FrankerZ的建议,您可能不需要callapply但是如果您需要更改上下文变量, 您可以使用call

var speak = function(iAmCat) {
  var iAmDog = this;
  console.log(iAmDog.love);
  console.log(iAmDog.normal);

  console.log(iAmCat.love);
  console.log(iAmCat.normal);
};

var speakAsDog = {
  normal: "moof",
  love: 'woow'
};
var speakAsCat = {
  normal: "meow",
  love: 'purr'
};

speak.call(speakAsDog, speakAsCat);

使用apply

var speak = function() {
  var iAmDog = this,
    iAmCat = arguments[0];
  console.log(iAmDog.love);
  console.log(iAmDog.normal);

  console.log(iAmCat.love);
  console.log(iAmCat.normal);
};

var speakAsDog = {
  normal: "moof",
  love: 'woow'
};
var speakAsCat = {
  normal: "meow",
  love: 'purr'
};

speak.apply(speakAsDog, [speakAsCat]);

使用bind

var speak = function(iAmCat) {
  var iAmDog = this;
  console.log(iAmDog.love);
  console.log(iAmDog.normal);

  console.log(iAmCat.love);
  console.log(iAmCat.normal);
};

var speakAsDog = {
  normal: "moof",
  love: 'woow'
};
var speakAsCat = {
  normal: "meow",
  love: 'purr'
};
var newFN = speak.bind(speakAsDog);
newFN(speakAsCat);