生活随笔
收集整理的這篇文章主要介紹了
ES5-8 闭包高级、对象、构造函数、实例化
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. 對(duì)象
- 對(duì)象內(nèi)定義的函數(shù)一般稱之為方法,在外部的函數(shù)聲明稱為函數(shù)
- 對(duì)象刪除屬性使用delete 關(guān)鍵字
var obj
= {a
: 1,b
: 'string'
}
console
.log('obj', obj
)
delete obj
.b
console
.log('obj', obj
)
- 在對(duì)象里,this指代這個(gè)對(duì)象本身
- 創(chuàng)建對(duì)象:使用對(duì)象字面量或者new Object()
- 自定義構(gòu)造函數(shù)應(yīng)用于:模塊化、插件化、組件化
- 只有new了構(gòu)造函數(shù)以后,this才存在,指向teacher對(duì)象,在實(shí)例化以前,GO里是沒(méi)有this的
- 通過(guò)構(gòu)造函數(shù)實(shí)例化出來(lái)的多個(gè)對(duì)象,他們之間是互不相同的
- 練習(xí)1:
function
myFun() {var sum
= 0var multi
= arguments
.length
=== 0 ?
0 : 1for (var i
= 0; i
< arguments
.length
; i
++) {sum
+= arguments
[i
]multi
*= arguments
[i
]}console
.log('累加/乘積', sum
, multi
)
}
myFun(1, 2, 3)
myFun(2, 0, 3)
function
MyFun() {var arg
= arguments
var resthis
.sumFn
= function
() {res
= 0loop('add', res
)}this
.multiFn
= function
() {res
= arg
.length
=== 0 ?
0 : 1loop('multi', res
)}function
loop(method
, res
) {for (var i
= 0; i
< arg
.length
; i
++) {if (method
=== 'add') {res
+= arg
[i
]} else if (method
=== 'multi') {res
*= arg
[i
]}}console
.log(method
== 'add' ?
'累加' : '累乘', res
)}
}
let funObj
= new MyFun(1, 2, 3)
funObj
.sumFn()
funObj
.multiFn()
let funObj2
= new MyFun(2, 0, 3)
funObj2
.sumFn()
funObj2
.multiFn()
var carOpts
= {expensive
: {brand
: '賓利',price
: 500},cheap
: {brand
: '吉利',price
: 10}
}
function
Car(carOpt
) {this
.brand
= carOpt
.brandthis
.price
= carOpt
.price
}
function
Customer(option
) {this
.name
= option
.namethis
.age
= option
.agethis
.salary
= option
.salarythis
.type = option
.typethis
.buy
= function
() {console
.log(option
.name
+ '買的車', new Car(carOpts
[option
.type]))}
}
var customerObj
= new Customer({ name
: '完顏洪烈', age
: 30, salary
: 1000, type: 'expensive' })
console
.log('客戶:', customerObj
)
customerObj
.buy()
var customerObj2
= new Customer({ name
: '楊康', age
: 18, salary
: 10, type: 'cheap' })
console
.log('客戶:', customerObj2
)
customerObj2
.buy()
總結(jié)
以上是生活随笔為你收集整理的ES5-8 闭包高级、对象、构造函数、实例化的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。