首页 > 文章列表 > javascript中原型对象this的原则

javascript中原型对象this的原则

JavaScript this 原型对象
182 2022-08-06

原则

1、只有当调用这个函数时,才能确定构造函数中的this指向谁。

2、一般来说,构造函数中的this指的是函数的调用者。

实例

 <script>
        function Star(uname, age) {
            this.uname = uname;
            this.age = age;
        }
        var that;
        Star.prototype.sing = function() {
            console.log('我会唱歌');
            that = this;
        }
        var ldh = new Star('刘德华', 18);
        // 1. 在构造函数中,里面this指向的是对象实例 ldh
        ldh.sing();
        console.log(that === ldh);
 
        // 2.原型对象函数里面的this 指向的是 实例对象 ldh
    </script>

推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。