JavaScript 中的 this, call, apply, bind...
2009-09-30 00:00:00 来源:WEB开发网但是不得不承认由this引起的错误代码还是会很容易就进来
看下面的代码
0. <script>
1. function test_handler(par){
2. this.par = par;
3. this.output = function(){
4. alert(this.par);
5. }
6. }
7. function addHandler(){
8. var obj = new test_handler("my paramters input");
9. document.getElementById("button1").onclick = obj.output;
10. }
11. window.onload = addHandler;
12. </script><input id="button1" value="click1" type="button">
很容易写出这样的代码。。。我们期望的结果肯定是alert出来my paramters input,但是实际上却是undefined
其实这里的错误就是最上面2种情况的综合,这里alert(this.par);中的this是button而不再是test_handler的instance了
2, call
先看一个最简单的例子
0. <script>
1. var first_json = {
2. first: 20
3. };
4. var first_obj = function(first){
5. this.first = first;
6. }
7. var obj = new first_obj(100);
8. function Calculate(secondNum){
9. return this.first * secondNum;
10. }
11. document.writeln(Calculate.call(1, 5)); //NaN: Not a number
12. document.writeln(Calculate.call({first:10}, 5)); //50
13. document.writeln(Calculate.call(first_json, 5)); //100
14. document.writeln(Calculate.call(obj, 5)); //500
15. </script>NaN
16. 50
17. 100
18. 500
NaN
50
100
500
Tags:JavaScript this call
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接