JavaScript使用this调用与直接对象调用的区别
迷茫
迷茫 2017-04-10 15:43:24
[JavaScript讨论组]

初学javascript,写了如下一个测试例子:

(function () {
    var Test = function() {
        this.name = "test";

/*语句块1
        this.prints = function (test) {
            console.log("In prints:"+test.name);
        };
*/
        console.log("in Test:"+this.name);
        this.prints(this); //语句1
        Test.prints(this); //语句2
        return this;
    };

/*语句块2
    //Test.prints = function (test) {
    //    console.log("In prints:"+test.name);
    //};
*/

    this.Test = Test;
}).call(this);

HTML页面很简单:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<script src="MyTest.js"></script>
<script>
    window.onload = function () {
        var test = new Test();
    }
</script>
</body>
</html>



使用语句1语句块1, 或者语句2语句块2时,能够正常调用prints函数:




但是使用语句1语句块2, 或者语句1语句块2时,则报错:




请问语句块1语句块2有什么区别吗?个人认为都是定义了对象的函数,二者应该没有什么不同才对。还请指教。

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(1)
高洛峰

Test函数中的this 为 使用new操作符号后关键的对象实例
而这个对象实例通过this.prints=function...赋值语句定义了一个prints函数
注意这个函数属于特定的Test实例对象

(function () {
    var Test = function() {
        this.name = "test";

        this.prints = function (test) {
            console.log("In prints:"+test.name);
        };

        console.log("in Test:"+this.name);
        this.prints(this); //语句1
        return this;
    };
    this.Test = Test;
}).call(this);

Test是一个函数,函数也是对象,同样也可以有属性,也可以在其中再定义函数
故Test.prints语句就是为Test函数对象定义了prints函数
通过Test.prints可以顺利被调用
Test函数对象和new Test()表达式生成的实例对象是2个不同的东东

(function () {
    var Test = function() {
        this.name = "test";
        Test.prints(this); //语句2
        return this;
    };
    Test.prints = function (test) {
        console.log("In prints:"+test.name);
    };
    this.Test = Test;
}).call(this);

其它的就好理解了~~~

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号