javascript对象学习笔记

  目前所见的,在普通的JavaScript应用中和绝大多数人一样使用的是全局的方式。大概是因为JavaScript所定义的变量或函数默认就是全局的。为了是代码不至于太凌乱,变量不至于稀里糊涂的就被人重定义或重新赋值,前段时间做了一个引入命名空间的形式的代码整改。

eg: var a=
{
     name:null,
    hellow:function(a)
    {
          return this.name+a;
    }
}

以上方式有个缺点,代码过于多或过于长、或过多人参与且编码无强制性规范要求时可能会出现属性中的变量和函数混合在一起。对此作以下方式的优化。

 1 eg:
 2 var a = {};
 3 a.propty={
 4       name:"",
 5       age: 0,
 6       ......
 7 }
 8 
 9 a.fn = 
10 {
11      hellow:function(a)
12      {
13           a =a || "";
14           return a.propty.name+a;
15       },
16      getage:function()
17      {
18           return a.propty.age;
19      }
20      ........
21 }
   变量和函数分离。
       以上方式中使用到了一种以前不曾用过的设置默认值的方式: a =a || "";以往习惯写成 a = a==null?"":a;
 
 
******************************以*****下*****是*****正*****题*********************************************

   1、JavaScript 对象定义方式     

 var AA = function (name,age) {
        this.Name = name||"";
        this.Age = age || "";
        this.Hellow = function ()
        {
            document.writeln("My name is " + this.Name + ",I'm " + this.Age);
        }

使用方式:

var b = new AA("c1", 11);
b.Hellow();

2、继承

createNew的启发:

注:上图原文地址:http://www.ruanyifeng.com/blog/2012/07/three_ways_to_define_a_javascript_class.html

受上述代码启发,写出了下面的代码:

 var AA = function (name,age) {
        this.Name = name||"";
        this.Age = age || "";
        this.Hellow = function ()
        {
            document.writeln("My name is " + this.Name + ",I'm " + this.Age );
        }

    };

 var AB = function (name,age) {
        var _ab = new AA(name,age);
        _ab.Talk = function () {
            document.writeln("I'm from BeiJin. I'm " + this.Age);
        };
        return _ab;
    }

使用:

 var ab = new AB("talk", 11); 
 ab.Talk(); ab.Hellow();

上述代码中的AB内部定义的_ab为AA新的实例,在这个实例上做扩展以达到继承的目的。

原文地址:https://www.cnblogs.com/aser1989/p/4191629.html