avatar

函数编写的几种方式

函数编写的几种方式

1
2
3
function checkName() {}
function checkEmail() {}
function checkPassword() {}

另外一种形式

1
2
3
var checkName = function() {}
var checkEmail = function() {}
var checkPassword = function() {}

把变量放到对象里面

1
2
3
4
5
6
7
var checkObject = {
checkName: function() {},
checkEmail: function() {},
checkPassword: function() {}
}

console.log(checkObject.checkName())

对象的另外一种形式

1
2
3
4
5
6
var checkObject = function() {}
checkObject.checkName = function() {}
checkObject.checkEmail = function() {}
checkObject.checkPassword = function() {}

console.log(checkObject.checkName())

调用函数时 返回一个新的对象

1
2
3
4
5
6
7
8
9
10
var checkObject = function() {
return {
checkName: function() { console.log(1) },
checkEmail: function() {},
checkPassword: function() {},
}
}

var test = checkObject()
test.checkName()

将对象看成类

1
2
3
4
5
6
7
8
var checkObject = function() {
this.checkName = function() { console.log(1) }
this.checkEmail = function() {}
this.checkPassword = function() {}
}

var test = new checkObject()
test.checkName()

挂载在原型,使之创建对象实例的时候,创建出来的对象所拥有的方法就都是一个

1
2
3
4
var checkObject = function() {}
checkObject.prototype.checkName = function() { console.log(1) }
checkObject.prototype.checkEmail = function() {}
checkObject.prototype.checkPassword = function() {}

另外一种写法

1
2
3
4
5
6
7
8
9
var checkObject = function() {}
checkObject.prototype = {
checkName: function() { console.log(1) },
checkEmail: function() {},
checkPassword: function() {}
}

var test = new checkObject()
console.log(test.checkName())

省去调用3个方法,减少书写3个test

1
2
3
4
5
6
7
var checkObject = {
checkName: function () { return this },
checkEmail: function () { return this },
checkPassword: function () { return this }
}

console.log(checkObject)

同样的方式放到类的原型对象中

1
2
3
4
5
6
7
8
9
var checkObject = function() {}
checkObject.prototype = {
checkName: function() { return 1 },
checkEmail: function() { return this },
checkPassword: function() { return this },
}

var test = new checkObject()
console.log(test.checkName())

在Function中添加

1
2
3
4
Function.prototype.checkName = function() { return 1 }

var test = function() {}
console.log(test.checkName())

抽象成统一的添加方法功能

1
2
3
4
5
6
7
8
Function.prototype.addMethod = function(name, fn) {
this[name] = fn
}

var methods = function() {}
methods.addMethod('checkName', function() {
console.log('do something~')
})

链式添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Function.prototype.addMethod = function(name, fn) {
this[name] = fn
return this
}

var methods = function() {}

methods.addMethod('checkName', function() {
return this
}).addMethod('checkEmail', function() {
return 2
})


console.log(methods.checkName().checkEmail())
文章作者: 张复明
文章鏈接: https://hexo.zhangaming.com/2020/05/06/func1/
版權聲明: 本博客所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 阿明的博客
打賞
  • 微信
    微信
  • 支付寶
    支付寶

評論