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()
接受两个参数name和profest,但我只是通过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引擎。
相关文章:
- 在表单提交将DOM的一部分替换为分部之后,我应该将ajax成功绑定到什么来使我的javascript工作
- 我可以'不要让Javascript工作不正常
- 如何让我的html5功能不兼容警告使用javascript工作
- Excel Web Services 电子邮件 JavaScript 工作表
- 用于Google Fusion Table层的Javascript工作,但试图整理代码
- Bootstrap:如何附加一个类,并且仍然有BS Javascript工作
- JavaScript 工作队列
- JavaScript工作,直到我添加这个&&陈述
- 为什么不'在CasperJS中没有简单的JavaScript工作
- 如何"递归AJAX回调”;在JavaScript工作中
- 基本验证javascript工作不正常
- 需要帮助让这个字符串的Javascript工作
- HTML和JavaScript工作不正常
- 下拉菜单无法从CSS或Javascript工作
- 需要从erb生成一个非常特定的html来让javascript工作
- 如果javascript代码段未使用,它将阻止其他javascript工作
- 将内联事件处理程序移动到chrome扩展的javascript工作表
- 阻止其他Javascript工作的Javascript
- iframe阻止javascript工作
- 无法获取切换函数(JavaScript工作)