问题一: 这个代码为什么alert出来是b?<html>
<head>
<script>
function a(item){
var aItem = item;
a.prototype.dis = function (){
alert( aItem );
}
}function showM(){
var list = {}
var aOBJ = new a("a");
var bOBJ = new a("b");
list["a"] = aOBJ;
list["b"] = bOBJ;
list["a"].dis();
}
</script>
</head>
<body onload="showM()" >
</body>
<html>问题2:var aItem 改成 this.aItem, 为什么有时候alert出来是undefined?
<head>
<script>
function a(item){
var aItem = item;
a.prototype.dis = function (){
alert( aItem );
}
}function showM(){
var list = {}
var aOBJ = new a("a");
var bOBJ = new a("b");
list["a"] = aOBJ;
list["b"] = bOBJ;
list["a"].dis();
}
</script>
</head>
<body onload="showM()" >
</body>
<html>问题2:var aItem 改成 this.aItem, 为什么有时候alert出来是undefined?
alert( aItem );
} 试看....
this.aItem = item;
a.prototype.dis = function (){
alert( this.aItem );
}
}
a.prototype.dis = function (){
alert( aItem );
} 应该换成
this.dis = function(){
alert( aItem);
}再品味一下这两个有什么区别!!
类 a
类的对象 aOBJ, bOBJ,....执行a.prototype.dis = function(){ };的结果:
a的所有对象( aOBJ, bOBJ,....)的dis方法都是刚设置的函数而执行aOBJ.dis = function(){ }的结果
只有对象aOBJ的dis方法被设置了,其他对象的都没有变
建议改成
function a(item){
this.aItem = item;
this.dis = function(){
alert(this.aItem);
};
}