JavaScript入门学习

《JavaScript入门学习》之生产环境中正确使用对象的姿势

2017-07-31  本文已影响7人  Johankoi

先来看一个例子

function Person() {
     this.name = 'chengxuyuan';
     this.age = 26;
     this.type = '人类';
     this.eat = function() {
          alert("吃老鼠");
      };
 }
 var p1 = new Person();
 var p2 = new Person();

通过Person创建了两个对象p1 p2,里面定义的属性方法在内存里面是两份。

p1.type == p2.type // false
p1.eat == p2.eat // false

在这个人类的实例中,type是'人类'这个属性,new出来的对象基本上都是这个值,
eat这个函数也是所有对象都有的行为,从业务性质讲是不变的,因此就每次要每次new都占用一份内存。
我们应该有一种机制,不论new多少次,某个类某些属性方法都共享一份,那么,前面学习的prototype就派上用场了~
因此正确的姿势就是这样:

function Person() {
     this.name = 'chengxuyuan';
     this.age = 26;
     Person.prototype.type = '人类';
     Person.prototype.eat = function () {
           console.log('吃饭');
     };
 }

// 也可以写在外面动态添加原型类的属性或者方法
Person.prototype.job = "coding";
Person.prototype.breath = function () {console.log('呼吸'); };

var p1 = new Person();
var p2 = new Person();

这样p1 , p2 的type,job属性,eat,breath方法,都指向同一个内存地址。
现在我们可以通过这种方案随心所欲的new出对象,实现js里面的面向对象程序设计,但通常实际生产环境中,我们不经常用new的方式创建对象。例如React Native里面View对象的源码(View.js) 里面:

const View = createReactClass({
  displayName: 'View',
  // TODO: We should probably expose the mixins, viewConfig, and statics publicly. For example,
  // one of the props is of type AccessibilityComponentType. That is defined as a const[] above,
  // but it is not rendered by the docs, since `statics` below is not rendered. So its Possible
  // values had to be hardcoded.
  mixins: [NativeMethodsMixin],

  // `propTypes` should not be accessed directly on View since this wrapper only
  // exists for DEV mode. However it's important for them to be declared.
  // If the object passed to `createClass` specifies `propTypes`, Flow will
  // create a static type from it. This property will be over-written below with
  // a warn-on-use getter though.
  // TODO (bvaughn) Remove the warn-on-use comment after April 1.
  propTypes: ViewPropTypes,
  ..................
});

创建对象的方法是通过createReactClass({ xx:xx , yy:xx ....});方式。
下面介绍这样的创建的对象姿势

最终正确的姿势

function Person(props) {
    this.name = props.name || 'people';    // 默认值为'匿名'
    this.age = props.grade || 1;      // 默认值为1
}

Person.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
};

function createPerson(props) {
    return new Person(props || {})
}

var p =  createPerson({
   name:'hanxiaoqing'
});

这样的creat xx函数不需要new来调用,因为有些时候我们会忘记写new,会造成类声明体内部的this找不到指向的对象,为undefined,造成问题会很严重。使用creat xx函数可以很好的避免这种问题。
还有一个好处就是参数非常灵活,不传值就是声明时候的可定制的默认值,如name,传值就覆盖默认值。

上一篇 下一篇

猜你喜欢

热点阅读