JavaScript使用this调用与直接对象调用的区别
迷茫
迷茫 2017-04-10 15:43:24
0
1
284

初学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有什么区别吗?个人认为都是定义了对象的函数,二者应该没有什么不同才对。还请指教。

迷茫
迷茫

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

reply all(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);

其它的就好理解了~~~

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!