借这篇文章理清一下自己的思路,同时也希望能给和我同样一知半解的同学理清一下思路。引发思考来自于我犯的一个错误,错误代码是这样的:
结果不用说,当然是报错的。遗憾的是我以前一直以为var o = { }是定义了一个叫做o的类。然后自己理了一下。得出一下结论:
var o = {}; 等价于 var o = new Object(); 但不等价于 var o = function(){};涞水县梁以纸业
第一二种形式 o是一个对象,Object类的对象。第三种形式 o是一个function,更重要的是o是一个类。
等价于
那问题是:对象上怎么可以直接定义属性呢?
由于o是Object类的对象,所以o.prototype是undefined 所以不能这样 o.prototype.oField = ...
另外,在思考过程中,我写了两段测试代码,一并贴上。可以算是个笔记吧。
02 |
var Engin = function (){}; |
05 |
Engin.prototype.objectField = "objectField" ; |
08 |
Engin.classField = "classField" ; |
11 |
Engin.prototype.objectMethod = function (){ |
12 |
document.write( "objectMethod is called<br/>" ); |
15 |
Engin.classMethod = function (){ |
16 |
document.write( "classMethod is called<br/>" ); |
20 |
new Engin().objectMethod(); |
25 |
document.write( new Engin().objectField + "<br/>" ); |
26 |
document.write(Engin.classField + "<br/>" ); |
30 |
document.write( "使用for in 遍历Engin对象===============================<br/>" ); |
32 |
document.write(o+ "<br/>" ); |
34 |
document.write( "=======================================================<br/>" ); |
02 |
var Parent = function (){ |
03 |
this .pField = "pField" ; |
04 |
this .pMethod = function (){ |
05 |
document.write( "pMethod is called<br/>" ); |
09 |
Parent.staticPField = "staticPField" ; |
11 |
Parent.staticPMethod = function (){ |
12 |
document.write( "staticPMethod is called<br/>" ); |
15 |
var Child = function (){ |
16 |
this .cField = "cField" ; |
17 |
this .cMethod = function (){ |
18 |
document.write( "cMethod is called<br/>" ); |
22 |
Child.staticCField = "staticCField" ; |
24 |
Child.staticCMethod = function (){ |
25 |
document.write( "staticCMethod is called<br/>" ); |
28 |
Child.prototype = new Parent(); |
31 |
var childObj = new Child(); |
32 |
document.write(childObj.pField+ "<br/>" ); |
36 |
document.write(childObj.cField+ "<br/>" ); |
37 |
document.write(Child.staticCField+ "<br/>" ); |
39 |
Child.staticCMethod(); |