JS中 self = this 的解释

拈花ヽ惹草 提交于 2020-02-07 08:13:14

DEMO 1

  function Person(){
        this.name = 'hjzgg';
        this.age = 24;

        this.show = function(){
            alert(name + " " + age);
        }
    }

    var p = new Person();
    p.show();

 错误:name 和 age都没有定义. 

DEMO 2

  function Person(){
        this.name = 'hjzgg';
        this.age = 24;

        this.show = function(){
            alert(this.name + " " + this.age);
        }
    }

    var p = new Person();
    p.show();

正确

DEMO 3

  function Person(){
        this.name = 'hjzgg';
        this.age = 24;

        this.show = function(){
            alert(this.name + " " + this.age);
        }
    }

    var p = new Person();
    p.show.call({});

错误:name 和 age 未定义

DEMO 4

  function Person(){
        this.name = 'hjzgg';
        this.age = 24;

        var self = this;

        this.show = function(){
            alert(self.name + " " + self.age);
        }
    }

    var p = new Person();
    p.show.call({});

正确

DEMO 5

  function Person(){
        this.sayHello = function(){
            alert('hello world!');
        }

        this.show = function(){
            sayHello();
        }
    }

    var p = new Person();
    p.show();

错误:sayHello()未定义

DEMO 6

  function Person(){
        var sayHello = function(){
            alert('hello world!');
        }

        this.show = function(){
            sayHello();
        }
    }

    var p = new Person();
    p.show();

正确

 

总结一下 :

 每个函数在定义被ECMAScritp 解析器解析时,都会创建两个特殊变量: this 和 arguments 。 

每个函数都有属于自己的this对象, 这个this 对象是在运行时基于函数的执行环境绑定的,即在全局对象中,this 指向的是window对象;在自定义函数中,this指向的是调用这个函数的对象,也就是说,谁调用这个函数对象,this就指向谁(this指向的是调用执行函数的那个对象)。如果是在函数嵌套环境中,this 指代的是调用外部函数或内部函数的执行环境对象  。

PS: 可以通过使用call() 和 apply() 改变函数执行环境的情况,改变this 指向

那么,为什么self.name 和 self.age 是正确的呢?

其实这又涉及到另一个话题:实例成员与局部成员。

我们创建构造函数的意义就是用它来创建实例,所有属于实例的成员都要用this 来定义;只有那些不属于实例的成员才不会用this 定义。只要用this 定义了方法以后,在函数作用域内部调用此方法时,就需要加上this了。

 

DEMO 7

 var person = {
        name : 'hjzgg',
        age : 24,
        show : function(){
            alert(name + " " + age);
        }

   }

   person.show();

错误:name 和 age 未定义

DEMO 8

 var person = {
        name : 'hjzgg',
        age : 24,
        show : function(){
            alert(this.name + " " + this.age);
        }

   }

   person.show();

正确

 

参考链接:

https://blog.csdn.net/wangchaohpu/article/details/82841739

https://www.cnblogs.com/hujunzheng/p/5330486.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!