js 继承带来的苦果!
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 //没想到啊!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 声明变量将会导致隐式的全局变量产生。
[解决办法]
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
};
这两个是一段等同的代码。