初学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
有什么区别吗?个人认为都是定义了对象的函数,二者应该没有什么不同才对。还请指教。
Test函数中的this 为 使用new操作符号后关键的对象实例
而这个对象实例通过this.prints=function...赋值语句定义了一个prints函数
注意这个函数属于特定的Test实例对象
Test是一个函数,函数也是对象,同样也可以有属性,也可以在其中再定义函数
故Test.prints语句就是为Test函数对象定义了prints函数
通过Test.prints可以顺利被调用
Test函数对象和new Test()表达式生成的实例对象是2个不同的东东
其它的就好理解了~~~