原型设置中 this 的疑惑

moliu 2009-11-30 09:41:15
function Collection(size)

{

this.size = function(){return size};

}



Collection.prototype.isEmpty = function(){ //这里的this指的是 Collection 还是 Collection.prototype ?

return this.size() == 0;//如果是Collection.prototype ,它能调用 Collection 的方法吗?

}//Collection.prototype 也是个对象啊
...全文
132 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
moliu 2009-12-02
  • 打赏
  • 举报
回复
var B={m:5};
function A(){}
A.prototype=B;
A.prototype.z=8;
b=new A();
alert(b.z); //output 8
alert(b.m); //output 5
alert(B.z); //output 8
for(S in B)
document.write(S+"="+B[S])//m=5z=8
dh20156 2009-12-01
  • 打赏
  • 举报
回复
关于this的最终回复,参见ECMA-262 10.2.3:


The caller provides the this value. If the this value provided by the caller is not an object (including the case where it is null), then the this value is the global object.


其他的参见Javascript Scope Chain相关资料。
zhangshaolongjj 2009-11-30
  • 打赏
  • 举报
回复
this指的是 new Collection()的对象
moliu 2009-11-30
  • 打赏
  • 举报
回复
function Point(dimension)

{

this.dimension = dimension;

}

//定义一个Point2D类型,“继承”Point类型

function Point2D(x, y)

{

this.x = x;

this.y = y;

}

Point2D.prototype.distance = function()

{

return Math.sqrt(this.x * this.x + this.y * this.y);

}

Point2D.prototype = new Point(2); //经过上面的设置,new Point(2)有distance 属性了吗?

87,993

社区成员

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

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