Js代码 【转】JavaScript的this 【转】JavaScript的this【转】JavaScript的this
  1. <script>   
  2.     function fooConstructor() {   
  3.         this.variable = 1;   
  4.     }   
  5.        
  6.     function makeAnonymousFunction() {   
  7.         return function() {   
  8.             this.gooValue = 2;   
  9.         };   
  10.     }   
  11.        
  12.     fooConstructor();          // invoke a function that looks like a constructor   
  13.     makeAnonymousFunction()(); // invoke an anonymous function   
  14.     document.write(variable + "<br />");   
  15.     document.write(window.gooValue + "<br />");   
  16.        
  17.     var obj = new fooConstructor(); // invoke a constructor with "new"   
  18.     document.write(obj.variable + "<br />");   
  19. </script>   
  20. <!-- displays:   
  21. 1   
  22. 2   
  23. 1   
  24. -->  
<script>
    function fooConstructor() {
        this.variable = 1;
    }
    
    function makeAnonymousFunction() {
        return function() {
            this.gooValue = 2;
        };
    }
    
    fooConstructor();          // invoke a function that looks like a constructor
    makeAnonymousFunction()(); // invoke an anonymous function
    document.write(variable + "<br />");
    document.write(window.gooValue + "<br />");
    
    var obj = new fooConstructor(); // invoke a constructor with "new"
    document.write(obj.variable + "<br />");
</script>
<!-- displays:
1
2
1
-->


虽然我们在第一次调用fooConstructor()时并没有以"object.method()"的形式来调用,它实际上等价于window.fooConstructor()。于是我们把window对象(浏览器DOM里的"全局"对象)隐式传给了所调用的函数,在fooConstructor里this就指向了window,并为window对象创建了variable属性,赋值为1。

makeAnonymousFunction()()的调用是为了演示这个this的指向与嵌套层次的无关性。makeAnonymousFunction()返回了一个函数对象,不过我们没有为这个对象给予一个名字,而是直接调用了它。与前一例一样,这个调用为window对象创建了一个名为gooValue的属性,并赋值为2。

然后我们演示了以new运算符来创建新对象的状况。这个很普通没什么需要解释的了~

相关文章:

  • 2021-10-20
  • 2022-12-23
  • 2021-12-05
  • 2021-08-28
猜你喜欢
  • 2021-12-09
  • 2021-06-25
  • 2022-12-23
  • 2021-12-04
  • 2021-05-17
相关资源
相似解决方案