返回 登录
3

JS构造函数模式

阅读2832

构造函数是可以创建特定类型对象的函数,可以接受参数定义函数成员。如果之前做过java比较好理解,举个例子:

function exampleFunction(arg1, arg2, arg3){
this.arg1 = arg1;
this.arg1 = arg1;
this.arg1 = arg1;
this.output = function(){
console.log(‘walk’ + arg3);
}
}
  用法是用new关键字创建实例:

var instance1 = new exampleFunction(12,32,90);
instance1.output() //walk 90
  需要注意的是,如果不用new会出现this被绑定到了window对象,上代码:

var instance2 = exampleFunction(1,2,3);
console.log(typeof instance2) //undefined
console.log(windows.output()) //walk 3
  有时候不想用new关键字,但是还是想实例化为exampleFunction,解决方式如下:

function exampleFunction(arg1, arg2, arg3){
if(!(this typeof exampleFunction)) {
return new exampleFunction(arg1, arg2, arg3);
}
this.arg1 = arg1;
this.arg1 = arg1;
this.arg1 = arg1;
this.output = function(){
console.log(‘walk’ + arg3);
}
}
  上述构造函数用起来调用output的时候每次都需要定义一个函数,比较占用内存,解决方式两种:

var a = new exampleFunction(1,2,3);
console.log(a.output()) //output function 被调用一次
var b = new exampleFunction(4,5,6)
console.log(b.output()) //output function 又被调用一次

解决方案一:
定义一个walk function,将其赋值给output,这样只用定义一次,但可多次调用
walk() {
console.log(‘walk’ + this.arg3);
}

构造函数里面this.output替换为this.output = walk;

解决方案二:

使用prototype,
exampleFunction.prototype.output = function() {
console.log(‘walk’ + this.arg3);
}

评论