javascript 直接创建对象与间接创建对象 私有函数不能访问this变量 是否使用var声明变量几个问题探讨

来源:互联网 发布:淘宝自动充值软件 编辑:程序博客网 时间:2024/05/20 15:57
<script type="text/javascript">var a = 'a1';var b = 'b1'function getA(){alert('1A')}var student = function (name,age){this.name = namethis.age = agethis.getName = function (){return this.name;}this.getAge = function(){return this.age;}var a = 'a2';b = 'b2';getA = function(){alert('A2')}getB = function(){alert('B')}}/**getA();alert(a)alert(b)new student();getA();alert(a)alert(b)//1.在student 类内如果不用var 来声明变量或者函数,那么会覆盖外面的变量或者函数,所以本函数内部的变量最好要使用var开始定义。**//**//getB()new student();getB()//2.在student没有被new之前是没有getB() 函数的**//**alert(new student('a',19).getName())new student('a',19).getA()//3.私有变量不能够被对象访问,而且私有方法不能够访问到对象变量的或者方法,也就是说在getA中不能访问name 或者getname**/var student1 = {name:'whs',//相当于this.nameage:10,getName:function (){return this.name;},getAge:function(){return this.age;}}var student2 = new student('whs',10)//4.student1 与 student2 表达的意思差不多,一个是通过直接创建对象的方式,一个是通过先创建函数(或者说类),再创建对象</script>