原型对象的this指向

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA_Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script>
        window.onload = function () {
            function Star(name,age) {
                this.name = name;
                this.age = age;
            }
            var that;
            Star.prototype.sing = function () {
                console.log('唱歌!');
                that = this;
            };
            var nlbf = new Star('nlbf',26);
            //1 在构造函数中,里面的this指向的是对象实例 nlbf
            nlbf.sing();
            console.log(that === nlbf);//true
            //2 原型对象函数里面的 this 指的是 实例对象 nlbf
        }
    </script>
</head>
<body>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_45949073/article/details/107427829