请教一个js的prototype机制的问题
在看一篇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 代码
- var a=function() {} ;
- a.prototype=function() {} ;
- a.prototype.prototype.test='a';
- var b=new a();
- alert(b.test);
但,并没有如文中所说那样,b.test还是undefined
不知道是我理解错了那段话,还是这段话是错的,希望有人来给我指点迷津,谢谢!
并且不应该相信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属性
var a=function(){} var temp=function (){} temp.prototype.temp=1234; a.prototype=new temp; b=new a; b.temp
ok,结贴,搞清楚那段英文原来是这个意思,就清楚了! 谢谢fins
但是那篇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 也无可厚非 呵呵. 只是他要是再配上源代码就好了.
呵呵
ls上说的原理我清楚 只是那段文章有点多的不清不楚
要这样:
实际上那篇文章里说了那么多, 就是在告诉我们在js中 常见的利用 prototype实现"继承"的原理 下面的代码和上面的其实同理.
var b=new a.prototype() 这样确实是可以访问到 当文中的原意是说js解释器会自动往下搜寻prototype 但实际上没有……哎
我记得那本书里也是这么说得,但是就像你测的那样会返回undefined,给我的感觉好像当你new a()时, a.prototype = function(){},这个匿名的function被追加到b上了,但a.prototype.prototype并没有,好像因为你没有new这个匿名的function,所以你的那个a.prototype.prototype并没有被付给b,所以b.test没定义
这样b.test就能访问了,