您好,欢迎访问一九零五行业门户网

JS设计模式之构造器模式详解

这次给大家带来js设计模式之构造器模式详解,js设计模式之构造器模式使用的注意事项有哪些,下面就是实战案例,一起来看一下。
经典的oop语言中,构造器(也叫构造函数)是一个用于初始化对象的特殊方法。在js中,因为一切皆对象,对象构造器经常被提起。
对象构造器用于建立制定类型(class)的对象,可以接受参数用于初始化对象的属性和方法。
对象建立
在js中,有三个常用的方法用于建立对象:
//1, 推荐使用 var newobject = {}; //2, var newobject = object.create( null ); //3, 不推荐 var newobject = new object();
但是,这也只是建立了三个空对象, 并没有任何属性和方法。我们可以通过以下四种方法,为对象设立属性和方法。
// ecmascript 3 兼容的方式 // 1. 常规对象定义方式 //设置属性 newobject.somekey = hello world; //获取属性 var key = newobject.somekey; // 2. 方括号方式 // 设置属性 newobject[somekey] = hello world; //获取属性 var key = newobject[somekey]; // 仅仅用于ecmascript 5 // 3. object.defineproperty // 设置属性 object.defineproperty(  newobject, somekey,  { value: for more control of the property's behavior,   writable: true,   enumerable: true,   configurable: true }); //可以通过下面的函数简化属性设置 var defineprop = function ( obj, key, value ){   config.value = value;   object.defineproperty( obj, key, config ); }; // 使用方法 var person = object.create( null );defineprop( person, car, delorean ); defineprop( person, dateofbirth, 1981 ); defineprop( person, hasbeard, false ); // 4. object.defineproperties //设置属性 object.defineproperties( newobject, { somekey: { value: hello world, writable: true },  anotherkey: { value: foo bar, writable: false } }); // 3和4的获取属性方法同1,2.
基本的构造器
我们知道, js中没有class的概念,但它也支持用构造器建立对象。
通过使用【new】关键字,我们可以使一个函数的举止类似于构造器,从而建立自己的对象实例。
一个基础的构造器形式如下:
function car( model, year, miles ) {   //这里,this指向新建立的对象自己   this.model = model;   this.year = year;   this.miles = miles;   this.tostring = function () {     return this.model +  has done  + this.miles +  miles;   }; } //用法 // 建立两个car实例 var civic = new car( honda civic, 2009, 20000 ); var mondeo = new car( ford mondeo, 2010, 5000 ); // 输出结果 console.log( civic.tostring() ); console.log( mondeo.tostring() );
这就是简单的构造器模式, 它有两个主要问题,
第一,它很难继承;第二,tostring()被每一个对象实例定义一遍,作为函数,它应该被每一个car类型的实例共享。
使用原型的构造器
js中有一个很好的特性:原型【prototype】,
利用它,建立对象时,所有构造器原型中的属性都可以被对象实例获得。
这样多个对象实例就可以共享同一个原型。
我们改善前面的car例子如下:
function car( model, year, miles ) {   this.model = model;   this.year = year;   this.miles = miles; } car.prototype.tostring = function () {   return this.model +  has done  + this.miles +  miles; }; // 用法 var civic = new car( honda civic, 2009, 20000 ); var mondeo = new car( ford mondeo, 2010, 5000 ); //输出 console.log( civic.tostring() ); console.log( mondeo.tostring() );
在上面的例子中,tostring()方法被多个car对象实例共享。.
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
angularjs实现select二级联动下拉菜单步奏详解
bootstrap与vue操作用户信息的添加与删除
以上就是js设计模式之构造器模式详解的详细内容。
其它类似信息

推荐信息