问题是这样的,javascript里面我可以自定义类 function A () { a = 10;}
然后增加方法 A.prototype.funcA=function(){ alert("123")};
之后创建对象 var obj = new A();
我通过for(var i in obj)现在能够获得 obj的属性和方法的名称,但是问题来了。
1.
我需要获得属性a的值 a= 10
2.
我需要获得funcA的方法体-> function(){alert("123")} 需要转换成字符串 而不是native code的形式
请问各位我该怎么实现,之前的constructor 和prototype都试验过不好用 该怎么办???
你那样申明a是全局变量,哪里都能访问,加var申明就变为内部变量,需要在A函数体内提供一个方法访问a,并且这个方法只能放A函数体中,不能通过prototype原型添加,这样访问不到
function A () {
var a = 10;
this.alertA=function(){alert(a)}
}
new A().alertA()
function A () { a = 10;} 中 a 是全局变量并不是属性
function A () { this.a = 10;}
这样才能 alert(obj.a)
obj.funcA() 是执行 funcA 方法
s = obj.funcA; //得到方法体
alert(s)
//1.constructor method
function A (a,b) {
this.a = a;
this.b = b;
this.funcA = function(){
alert("123");
}
}
var boy1 = new A("martin",10);
alert(boy1.a) //属性
alert( boy1.funcA +""); //方法体
//2.prototype add method
function A (a) {
this.a = a;
}
A.prototype.funcA=function(){ alert("123")};
var boy2 = new A("martin",10);
alert(boy2.a) //属性
alert( boy2.funcA+""); //方法体