我能够得到第一个参数iAmDog
,this
也可以访问第一个参数,如何传递第二个参数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);
答案 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.call
和function.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的建议,您可能不需要call
或apply
但是如果您需要更改上下文变量,
您可以使用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);