日期:2014-05-16  浏览次数:21476 次

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