[英]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.