js 继承带来的苦果!该如何解决
js 继承带来的苦果!JScript codevar Point function() {this. x 1this. y 1this.setPoint funct
js 继承带来的苦果!
JScript codevar 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函数里没有初始化。
[解决办法]围观
[解决办法][解决办法]其实你这个继承的实现模式没有错,这个模式是借用构造函数来实现继承的。
错在this.x和x的理解。
JScript codevar 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 声明变量将会导致隐式的全局变量产生。
[解决办法]
[解决办法]
[解决办法]
[解决办法]
JScript codefunction 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
};
这两个是一段等同的代码。