还是继承的问题,求助

tjp32 2014-01-09 05:06:36
先看2段代码
(1)
function Man(age) {
this.age = age;
};

Man.prototype.show = function () {
alert(this.age);
};

function Women(age) {
this.age = age;
}
Women.prototype = new Man();
Women.constructor = Women;

var test = new Women("20");
test.show();//没有什么问题显示20
----------------------
(2)
var a=function Man(age) {
this.age = age;
};

Man.prototype.show = function () {
alert(this.age);
};

function Women(age) {
this.age = age;
}
Women.prototype = new a();
Women.constructor = Women;

var test = new Women("20");
test.show();
//为什么仅仅修改了红色部分,就提示没有此方法
//我的理解是,Man构造函数赋给了一个变量a,然后new a()和new Man()不是一样的效果马?!
//为什么不能继承方法阿,其指点!
...全文
145 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
阿鱼 2014-01-10
  • 打赏
  • 举报
回复

var a=function Man(age){
   this.age = age; 
};
//虽然这里有“function Man(age){..}”,但是这只是语句的一部分,而整个这个语句是个
//赋值表达式(给变量a赋值)所以“function Man(age){..}”并不会起到函数声明的作用。
//整句等价于“var a=function(age){..}”,既然不是函数声明 
//Man也就不是个函数了,那么“Man”这个标识符在这里就已经毫无意义。
//实际上当代吗执行到“Man.prototype.show...”的时候就已经报错了:
//“Uncaught ReferenceError: Man is not defined”,下面的根本都还没执行
如果用“new a()”来实例化对象也是可以的,不过“Man.prototype”要改成“a.prototype”
tjp32 2014-01-10
  • 打赏
  • 举报
回复
xyz is going to be defined as usual, abc is undefined in all browsers but IE — do not rely on it being defined. But it will be defined inside its body: var xyz = function abc(){ // xyz is visible here // abc is visible here } // xyz is visible here // abc is undefined here 我X,果然还是正规定义比较好
JavaScript_R 2014-01-09
  • 打赏
  • 举报
回复
把 var a=function Man(age){ this.age = age; }; 改为 function Man(age){ this.age = age; }; var a=Man; 就可以了
zhjdg 2014-01-09
  • 打赏
  • 举报
回复
不是a 没有,是Man没有。 至于Man,在旧的IE浏览器中,好像是有。 http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname xyz is going to be defined as usual, abc is undefined in all browsers but IE — do not rely on it being defined
tjp32 2014-01-09
  • 打赏
  • 举报
回复
嗯,也有可能哦,有大神在吗
张运领 2014-01-09
  • 打赏
  • 举报
回复
你这想法还真是奇特,不过我还真是没有想过可以这么写。 我猜测吧,这不能实现的原因应该跟函数定义的这种方法有关,var a = function(){}; 跟这种定义函数的方法有关,具体什么关系,没有想过,现在也说不了啥。 猜测一下吧: 构造函数的写法,和赋值的函数写法的本质不同,就是,构造函数的写法,会在预编译的时候,就会执行了。 而赋值的写法,只有当解析到这个赋值语句的时候,才会执行。 那么你这里的那个构造函数,你觉得是在编译的时候,就存在了吗?我觉得应该不是吧。 那么既然不是,他就跟构造函数的那种函数定义方法,在本质上就不同了,所以这里,它也不能算是一个构造函数了吧? 那既然不是,它怎么能当做构造函数使用呢? 编程语言嘛,肯定都是有自己的规则的,那既然这样的写法是不符合规则的,那么肯定就会被处理掉了啊。 差不多就是这样,个人猜测,仅供参考。

87,997

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧