繁体   English   中英

function.apply如何在javascript中工作

[英]how function.apply works in javascript

我只是尝试使用javascript中的function.apply() ,无法理解它如何解析我们传入的数组参数。例如,

var update = function(name, profession){
    this.name = name;
    this.profession = profession;
}

var p1 = {
    name : "bond", 
    profession : "actor"
}

console.log(p1.name, p1.profession);  //outputs bond actor

现在让我们使用apply()方法更改p1的属性

update.apply(p1, ["john", "developer"]);

第一个参数是this指针的值,第二个参数是一个array

console.log(p1.name, p1.profession);  //outputs john developer

函数update()接受两个参数名称和名称,但是我只是通过apply()方法向其传递一个array参数["john", "developer"] 我不明白我的update()方法如何正确地从传入的数组中捕获属性,并相应地更新每个属性。

谢谢!

通过展开数组并将该数组的每个元素作为不同的参数传递来apply工作。 这完全取决于它们在数组中出现的顺序。

例:

 function printThings(pre, a, b, c) { var el = document.querySelector('pre'); // Put the text into an element el.innerHTML += pre + '> 1: ' + a + '\\n'; el.innerHTML += pre + '> 2: ' + b + '\\n'; el.innerHTML += pre + '> 3: ' + c + '\\n\\n'; } // Calling it normally printThings('Normal', 'A', 'B', 'C'); // Call using apply // Notice how the array is in the same order as when we called it normally printThings.apply(null, ['Apply (1)', 'A', 'B', 'C']); // Now we'll rearrange the arguments printThings.apply(null, ['Apply (2)', 'C', 'A', 'B']); 
 <pre></pre> 

还值得一提的是,传递了apply的第一个论点。 在前面的示例中,我传入了null因为我根本没有在函数内部使用this函数。 但是如果我是呢? 然后,我可以将this作为第一个参数传递的值。

 function printThings(pre) { var el = document.querySelector('pre'); // Here, we expect "this" to be an object with a, b, and c properties el.innerHTML += pre + '> A: ' + this.a + '\\n'; el.innerHTML += pre + '> B: ' + this.b + '\\n'; el.innerHTML += pre + '> C: ' + this.c + '\\n\\n'; } // Passing in null defaults to using the global context printThings.apply(null, ['Global']); // Notice how they're all undefined since there are no a, b, or c properties on the global scope // But now we'll pass it an object with some values printThings.apply({ a: 'A', b: 'B', c: 'C' }, ['Matching Values']); // And just to drill the point home, here's an object with the right properties but different values printThings.apply({ a: 'Here', b: 'We', c: 'Go' }, ['Different']); 
 <pre></pre> 

它是如何工作的具体细枝末节取决于你在运行它的JS引擎。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM