JS 对象封装的常用方式

JS 对象封装的常用方式

JS是一门面向对象语言,其对象是用prototype属性来模拟的。来看看如何封装JS对象.

常规封装

1
2
3
4
5
6
7
8
9
10
11
12
function Person (name,age,sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
}
 
Pserson.prototype = {
    constructor:Person,
    sayHello:function(){
        console.log('hello');
    }
}

 这种方式是比较常见的方式,比较直观,但是Person() 的职责是构造对象,如果把初始化的事情也放在里面完成,代码就会显得繁琐,如果放在一个方法里初始化会不会好点呢?

 

升级版 (常见)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function Person (info){
    this._init_(info);
}
 
Pserson.prototype = {
    constructor : Person,
    _init_ : function(info) {
        this.name = info.name;
        this.age = info.age;
        this.sex = info.sex;
    }
    sayHello:function(){
        console.log('hello');
    }
}

 可是,说到这里就发现,name,age,sex 并没有在Person里面申明,哪来的呢???

 

new 的执行原理

new 的执行过程可以用下面一个函数来代替

1
2
3
4
5
6
7
8
9
10
var myNew = function(constructor, args) {
       var o = {};
       o.__proto__ = constructor.prototype;
       var res = constructor.apply(o, args);
       var type = typeof res;
       if (['string', 'number', 'boolean', 'null', 'undefined'].indexOf(type) !== -1) {
           return o;
       }
       return res;
   }

 

解释:
首先通过 var o = {} 构造一个空对象.
然后将 构造函数的原型属性prototype赋值给o 的原型对象__proto__ 。这样,在执行 this.init(info); 这句话的时候,对象 o 就可以在其原型对象中查找_init_ 方法。(原型链)。
之后这句话 就是精髓了。

1
var res = constructor.apply(o,args);

 以o为上下文调用函数,同时将参数作为数组传递。那么,

1
this._init_(info);

 这句话就会被 o 执行,函数

1
2
3
4
5
_init_ : function(info) {
       this.name = info.name;
       this.age = info.age;
       this.sex = info.sex;
   }

 

以 o 为上下文调用,o也将拥有自己的 name,age,sex 属性。

如果在构造函数中,return 复合类型,包括对象,函数,和正则表达式,那么就会直接返回这个对象,否则,返回 o

1
2
3
4
5
var type = typeof res;
    if(['string','number','boolean','null','undefined'].indexOf(type) !== -1){
        return o;
    }
    return res;

 测试一下

1
2
3
4
5
6
7
8
9
function Person(name) {
     this.name = name;
 }
 Person.prototype.sayHello = function() {
     console.log(this.name);
 }
 var o1 = myNew(Person, ['pawn']);
 console.log(o1);
 o1.sayHello();

 

 

 

call方法:
语法:call([thisObj[,arg1[, arg2[,   [,.argN]]]]])
定义:调用一个对象的一个方法,以另一个对象替换当前对象。
说明:
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。
如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。

apply方法:
语法:apply([thisObj[,argArray]])
定义:应用某一对象的一个方法,用另一个对象替换当前对象。
说明:
如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。
如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。

 

 

 

类jQuery 封装

 

 这种方式是我从 jQuery 那里学来的。

jQuery 对象具有很强的集成性,可以作为函数调用,也可以做为对象调用,当作为函数调用的时候,她可以无需 new 而返回它的一个实例,很方便。

代码

1
2
3
4
5
6
7
8
9
10
11
var Person = function(info){
    return new Person.prototype.init(info);
}
 
Person.prototype = {
    constructor: Person,
    init:function(){
        this.name = info.name.
    }
}
Person.prototype.init.prototype = Person.prototype;

 这种封装方式非常巧妙。
将对象的构造操作放在函数的里面,而自己充当一个工厂。
不断调用 prototype 并不是一个直观的做法,于是

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var Person = function(info){
    return new Person.fn.init(info);
}
 
Person.fn = Person.prototype = {
    constructor: Person,
    init:function(){
        this.name = info.name;
        this.sayHello = function(){
            this.makeArray();
        }
    }
    makeArray:function(){
        console.log(this.name);
    }
}
// 这句话的作用
// 虽然把makeArray 等常用方法挂载到 Person.prorotype 下面,但还是会被 init 这个实例使用.
Person.fn.init.prototype = Person.fn;

 最后用 闭包 封装起来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var Person = (function(window) {
        var Person = function(name) {
            return new Person.fn.init(name);
        }
 
        Person.fn = Person.prototype = {
            constructor: Person,
            init: function(name) {
                this.name = name;
                this.sayHello = function() {
                    this.makeArray();
                }
            },
            makeArray: function() {
                console.log(this.name);
            }
        }
 
        Person.fn.init.prototype = Person.fn;
 
        return Person;
    })();

 测试一下

1
2
3
var p = Person('pawn');
   console.log(p);
   p.sayHello();

 

 

 

object.create()

js也提供了一种构造对象的方式,object.create(); 可以传递一个对象Person,构造一个p,并且使p 继承Person.

1
2
3
4
5
6
7
8
9
var Person = {
      name: 'pawn',
      sayHello: function() {
          console.log(this.name);
      }
  }
  var p = Object.create(Person);
  console.log(p);
  p.sayHello();

 

 

 

可以看到,对象Person的属性成为了p的原型属性,也就是说 p 原型继承自 Person !

我们可以实现一个 Object.create()

1
2
3
4
5
6
Object.create = function(prototype){
   function Func(){};
   Func.prototype = prototype;
   var o = new Func();
   return o;
}

 在这里,我们将 Person 作为 构造函数的 原型属性,就可以构造出 以Person 为原型对象的对象.

 

posted on 2017-12-26 10:37  Windy心梦无痕  阅读(5343)  评论(0编辑  收藏  举报