JavaScript中的this问题

1.以函数形式调用时,this永远都是window

<script type="text/javascript">
    var name = "全局的name属性";            
    function fun(){
        console.log(this.name);
    }            
    fun();            
</script>

2.以方法的形式调用时,this是调用方法的对象

<script type="text/javascript">            
    function fun(){
        console.log(this.name);
    }            
    //创建一个对象
    var obj = {
        name:"孙悟空",
        sayName:fun
    };        
    console.log(obj.sayName == fun);
    var name = "全局的name属性";
    //以函数形式调用,this是window
    fun();            
    //以方法的形式调用,this是调用方法的对象
    obj.sayName();            
</script>

3.以构造函数的形式调用时,this是新创建的那个对象

<script type="text/javascript">
    function Person(name , age , gender){
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.sayName = function(){
            alert(this.name);
        };
    }            
    var per = new Person("孙悟空",18,"男");            
    console.log(per);    
</script>

4.使用call和apply调用时,this是指定的那个对象

<script type="text/javascript">
  function Person(color) {
    console.log(this)
    this.color = color;
    this.getColor = function () {
      console.log(this)
      return this.color;
    };
    this.setColor = function (color) {
      console.log(this)
      this.color = color;
    };
  }
  var p = new Person("yello"); 
  var obj = {};
  p.setColor.call(obj, "black"); //this是谁? obj
</script>

 

posted @ 2022-04-13 11:39  城南以南123  阅读(31)  评论(0编辑  收藏  举报