论坛首页 Web前端技术论坛

请教一个js的prototype机制的问题

浏览 4236 次
精华帖 (0) :: 良好帖 (1) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-09-07  

在看一篇js的论文时,看见这么一段话:
When reading property p of object x using the expression x.p, the object x is searched first for a property named p. If there is one, its value is returned; if not, x’s prototype (let’s call it y) is searched for a property named p. If there isn’t one, y’s prototype is searched next and so on. If no property at all is found, the result is the value undefined.

于是,我用下面的代码测试了下:

js 代码
  1. var a=function() {} ;   
  2. a.prototype=function() {} ;   
  3. a.prototype.prototype.test='a';   
  4.   
  5. var b=new a();   
  6. alert(b.test);   
但,并没有如文中所说那样,b.test还是undefined
不知道是我理解错了那段话,还是这段话是错的,希望有人来给我指点迷津,谢谢!
   发表时间:2007-09-07  
我记得那本书里也是这么说得,但是就像你测的那样会返回undefined,给我的感觉好像当你new a()时,
a.prototype = function(){},这个匿名的function被追加到b上了,但a.prototype.prototype并没有,好像因为你没有new这个匿名的function,所以你的那个a.prototype.prototype并没有被付给b,所以b.test没定义
var b=new a.prototype();  

这样b.test就能访问了,
0 请登录后投票
   发表时间:2007-09-07  
var b=new a.prototype()
这样确实是可以访问到
当文中的原意是说js解释器会自动往下搜寻prototype
但实际上没有……哎
0 请登录后投票
   发表时间:2007-09-07  
要这样:
<script language="JavaScript">

var a=function() {} ; 
var aa=function() {} ;
aa.prototype.test='a';   
a.prototype=new aa();
 
var b=new a();    
alert(b.test);   

</script>


实际上那篇文章里说了那么多, 就是在告诉我们在js中 常见的利用 prototype实现"继承"的原理
下面的代码和上面的其实同理.
var aa={
	test : "a"
};

a.prototype=aa;

var b=new a();    
alert(b.test);   

0 请登录后投票
   发表时间:2007-09-07  
ls上说的原理我清楚
只是那段文章有点多的不清不楚
0 请登录后投票
   发表时间:2007-09-07  
但是那篇E文说的没错
你运行一下:

alert(b.constructor.prototype.test);  

alert(b.constructor.prototype.constructor.prototype.test);  

都打出"a"了.


原文中的 "x’s prototype "
并不是 x的prototype  而是 x这个对象对应的类的prototype
也就是constructor.prototype
我们应该把x理解为类 而不要理解为对象.

但是js中没有类的概念,所以作者用object 也无可厚非 呵呵.
只是他要是再配上源代码就好了.

呵呵
0 请登录后投票
   发表时间:2007-09-07  
ok,结贴,搞清楚那段英文原来是这个意思,就清楚了!
谢谢fins
0 请登录后投票
   发表时间:2007-09-07  
var a=function(){}
var temp=function (){}
temp.prototype.temp=1234;
a.prototype=new temp;
b=new a;
b.temp
0 请登录后投票
   发表时间:2007-09-07  
并且不应该相信constructor属性,见下面例子
a=function(){}
a.prototype.b=123;
b=new a;
b.constructor==a //true


a=function(){}
a.prototype={b:123}
b=new a
b.constructor==a //false
b.constructor==Object //true
b.constructor==a.prototype.constructor //true
目前看来,new的对象是原构造函数的prototype的构造函数为constructor属性
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics