ITeye博客

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

ajaxgo · 2007-09-07 11:16 · Web前端 · prototype · Markdown

在看一篇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. var b=new a();
  5. alert(b.test);

但,并没有如文中所说那样,b.test还是undefined
不知道是我理解错了那段话,还是这段话是错的,希望有人来给我指点迷津,谢谢!

评论(8)

  1. #8 楼 · afcn0 · 2007-09-07 15:03

    并且不应该相信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属性

  2. #7 楼 · afcn0 · 2007-09-07 15:01

    var a=function(){} var temp=function (){} temp.prototype.temp=1234; a.prototype=new temp; b=new a; b.temp

  3. #6 楼 · ajaxgo · 2007-09-07 13:45

    ok,结贴,搞清楚那段英文原来是这个意思,就清楚了! 谢谢fins

  4. #5 楼 · fins · 2007-09-07 13:36

    但是那篇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 也无可厚非 呵呵. 只是他要是再配上源代码就好了.

    呵呵

  5. #4 楼 · ajaxgo · 2007-09-07 13:12

    ls上说的原理我清楚 只是那段文章有点多的不清不楚

  6. #3 楼 · fins · 2007-09-07 12:59

    要这样:

    
    <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);   
    
    
    
  7. #2 楼 · ajaxgo · 2007-09-07 12:42

    var b=new a.prototype() 这样确实是可以访问到 当文中的原意是说js解释器会自动往下搜寻prototype 但实际上没有……哎

  8. #1 楼 · campaign · 2007-09-07 11:55

    我记得那本书里也是这么说得,但是就像你测的那样会返回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就能访问了,

评论功能维护中,当前仅展示历史评论。