對(duì)象
1. 概念
ECMA-262把對(duì)象定義為:“無序?qū)傩缘募希鋵傩钥梢园局怠?duì)象或者函數(shù)∏恳”
對(duì)象 = 屬性 + 方法
2. 創(chuàng)建對(duì)象的N中方式
-
構(gòu)造函數(shù)模式
var obj = new Object(); obj.name = 'Modeest'; obj.say = function () { console.log('hello world'); } console.log(obj.name); obj.say();
-
對(duì)象字面量模式
var obj = { name: 'Modeest', say: function () { console.log('hello world'); } } console.log(obj.name); obj.say();
ES6對(duì)字面量進(jìn)行了簡化
- 屬性名跟變量名相同,可以簡寫
- 方法名省略function關(guān)鍵字
var name = 'Modeest';
var obj = {
name,
say () {
console.log('hello world');
}
}
console.log(obj.name);
obj.say();
-
構(gòu)造函數(shù)模式
function Person () { this.name = 'Modeest'; this.say = function () { console.log('hello world'); } } var obj = new Person(); console.log(obj.name); obj.say();
-
Class模式(ES6)
class Person { constructor (name) { this.name = name; } say () { console.log('hello world'); } } var obj = new Person('Modeest'); console.log(obj.name); obj.say();
3. 注意
-
調(diào)用屬性
obj.name // 等價(jià)于上面的obj.name var key = 'name'; obj[key]
-
調(diào)用方法
obj.say() // 等價(jià)于上面的obj.say() var key = 'say'; obj[key]()
4. 優(yōu)點(diǎn)
- 給函數(shù)傳遞大量可選參數(shù)为黎,使用對(duì)象很方便
5. Object方法
-
defineProperty:定義單個(gè)屬性
var person = {}; Object.defineProperty(person, "name", { writable: true, // 是否可修改 configurable: false, // 是否可以刪除屬性 enumerable: true, // 是否可以枚舉屬性 value: 'Modeest', // 設(shè)定name的值 get: function () { // 獲取name調(diào)用的鉤子 return this.name; }, set: function (newValue) { // 修改name調(diào)用的鉤子 if (newValue === 'Modeest') { this.name = 'modeest-1'; } } }) 注意: 1. 默認(rèn)情況下邮丰,上述的writable,configurable铭乾,enumerable都為false 2. 上述屬性如果設(shè)置為false剪廉,在非嚴(yán)格模式下忽略,在嚴(yán)格模式下報(bào)錯(cuò) 3. 定義屬性的configurable為false炕檩,再調(diào)用defineProperty修改configurable時(shí)也會(huì)直接報(bào)錯(cuò)
-
Object.defineProperties():定義多個(gè)屬性
var person = {}; Object.defineProperties(person, { name: { value: 'modeest' }, age: { value: 18 } })
-
Object.getOwnPropeertyDescriptor():讀取屬性的特性
Object.getOwnPropeertyDescriptor(person, 'name');
6. 關(guān)于構(gòu)造函數(shù)
function Person (name, age) {
this.name = name;
this.age = age;
this.say = function () {
alert(this.name);
}
}
var p = new Person('Modeest', 18);
instanceof:判斷對(duì)象是否是類的實(shí)例化對(duì)象
p instanceof Person;
此處有個(gè)面試題:判斷某個(gè)值是否是對(duì)象的方法斗蒋,多種實(shí)現(xiàn)方法
(設(shè)計(jì)模式,原型笛质,繼承)未完待續(xù)泉沾。。妇押。