首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

js 继承带来的苦果!该如何解决

2012-04-01 
js 继承带来的苦果!JScript codevar Point function() {this. x 1this. y 1this.setPoint funct

js 继承带来的苦果!

JScript code
var Point = function() {    this. x = 1;    this. y = 1;    this.setPoint = function(px, py) { x = px; y = py; };    this.showPoint = function() { alert("x=\t" + x + "\ny=\t" + y); };};var ColorPoint = function(){    this.color = "#FFFFFF";    Point.call(this); //this 指的是Obj};var p1= new ColorPoint();p1.setPoint(5,5);p1.showPoint(); //这里是 "x = 5   y = 5"alert(p1.x);   //这里是 1  //没想到啊!

//气死我了,没想到啊!

[解决办法]
this.setPoint = function(px, py) { this.x = px; this.y = py; };
this.showPoint = function() { alert("x=\t" + this.x + "\ny=\t" + this.y); };
[解决办法]
你这样子搞,x和y都是全局变量,因为你Point函数里没有初始化。

[解决办法]
围观
[解决办法]
探讨

再 啰嗦一句:
Point.call(this); //this 指的是Obj
这一行,js 究竟干了什么?

是这样吗?下面的 两种等效吗?
JScript code
var Point = function() {
this. x = 1;
this. y = 1;
this.setPoint = function(px, py) { this.x……

[解决办法]
其实你这个继承的实现模式没有错,这个模式是借用构造函数来实现继承的。
错在this.x和x的理解。
JScript code
var Point = function() {            this. x = 1;            this. y = 1;            this.setPoint = function(px, py) { x = px; y = py; };//这个x,y是在全局变量中定义的            this.showPoint = function() { alert("x=\t" + x + "\ny=\t" + y); };        };
[解决办法]
不使用 var 声明变量将会导致隐式的全局变量产生。
[解决办法]
探讨

谢谢 上面各位了!
现在已把 《javaScript 王者归来》 看完了。
似懂非懂的,
想问问 下面的继承的call的返回值是什么?
JScript code
function Class3()
{
this.alertText= function(txt)
{
alert(txt);
}
}
function Class5()
{
……

[解决办法]
探讨

引用:

再 啰嗦一句:
Point.call(this); //this 指的是Obj
这一行,js 究竟干了什么?

是这样吗?下面的 两种等效吗?
JScript code
var Point = function() {
this. x = 1;
this. y = 1;
this.setPoint = function(px,……

[解决办法]
探讨

引用:

引用:

再 啰嗦一句:
Point.call(this); //this 指的是Obj
这一行,js 究竟干了什么?

是这样吗?下面的 两种等效吗?
JScript code
var Point = function() {
this. x = 1;
this. y = 1;
th……

[解决办法]
JScript code
function a(){  this.a = "123"}function b(){  a.call(this) //执行a,伪造a的this指向当前对象//以下就可以访问a内部的东西了}alert((new b()).a) //123
[解决办法]
var ColorPoint = function(){

this.color = "#FFFFFF ";
Point.call(this); //this 指的是Obj
};

你的这个其实就是定义一个类,类似java中的类。里面的this指向当前的对象,而不是window。其实你的这段代码如果这样写会更清楚一些
function ColorPoint (){

this.color = "#FFFFFF ";
Point.call(this); //this 指的是Obj


};

这两个是一段等同的代码。

热点排行