当前位置:编程学习 > JS >>

js类中的公有变量和私有变量

答案:在cnblogs上看了关于js的一些文章 ,做下笔记:

先看代码1:
function car(){
var wheel = 3;//私有变量
this.wheel = 4;//公有变量
alert(wheel);
alert(this.wheel);
}
var car1 = new car();结果是:3 4

代码2:
function car(){
var wheel = 3;//私有变量
this.wheel = 4;//公有变量
}
var car1 = new car();
alert(car1.wheel);结果:4

var wheel = 3是局部变量,this.wheel=4是公有变量,若想访问car中的私有变量,请看代码3:
function car(){
var wheel = 3;//私有变量
this.wheel = 4;//公有变量
this.getPrivateVal = function(){
return wheel;
}
}
var car1 = new car();
alert(car1.getPrivateVal());结果:3

上一个:javascript 兼容FF的onmouseenter和onmouseleave的代码
下一个:javascript 支持ie和firefox杰奇翻页函数

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,