function Na(name){this.name=name}
function Se(){this.sex="male"}
A.prototype=new Se;
var A=new Na("li");
var B=new Se;
alert(A.sex);
为什么A.prototype=new Se;这条语句只能放在var B=new Se的前面,而不能放在后面呢???还有为什么不可以用A.prototype=Se;非得加一个new,不能直接用类名呢?[size=large][/size]
new Se 等价于new Se();表示创建一个对像
Se 表示一个函数的定义
Se(); 表示执行一个函数
你可以这样试着写
function Se(){alert(this)}
当执行new Se()和执行Se()时就可以看出一些差别
Na.prototype=new Se 表示Na 继承new Se创建的对像
Na.prototype=Se 表示Na 继承Se函数
Na.prototype=Se() 表示Na继承Se函数执行的结果,在这里因为Se函数的返回值是void所以就是undefined。如果 你把Se定义成这样
function Se(){return {a:'xxxx'}}
那吗Na.prototype=Se 表示Na继承{a:'xxxx'}
你这段代码我跑了都报错的
Uncaught TypeError: Cannot set property 'prototype' of undefined
1.[code="java"]Na.prototype=new Se;
[/code]
这个的意思是让Na继承Se. 你放在后面了,你的A对象就没有Se的sex属性,
所以alert(A.sex); 就报undefined。
2.new 这个关键字,是必须的。
3.参照和学习方法:
参照网址:[code="java"]http://tech.ddvip.com/2009-05/1243588303121461.html[/code]
代码练习网址:
[code="java"]http://www.w3school.com.cn/tiy/t.asp?f=jseg_prototype[/code]
你可以把代码拷到W3CSchool的上述网址中观察练习结果。