JavaScript建立物件的多種方法

嘩啦啦啦發表於2021-11-07

方法一 ----通過字面量建立

let obj = {
    name: 'zhang',
    age: 12,
    sayName: function () {
        console.log(this.name);
    }
}
console.log(obj);//{ name: 'zhang', age: 12, sayName: [Function: sayName] }

方法二 ----用function來模擬無參的建構函式

function Person() { }
//定義一個function,如果使用new"例項化",該function可以看作是一個Class
let person = new Person()
//給person物件例項新增屬性
person.name = 'zhang'
person.age = 13
person.sayName = function () {
    console.log(this.age);
}
console.log(person);//Person { name: 'zhang', age: 13, sayName: [Function (anonymous)] }

方法三 ----自定義建構函式(有參)

function Dog(name, age, color) {
    this.name = name
    this.age = age
    this.color = color
    this.sayName = function () {
        console.log(this.name);
    }
}
let dog1 = new Dog('luky', 2, 'yellow')
console.log(dog1);  //Dog {name: 'luky',age: 2,color: 'yellow',sayName: [Function (anonymous)] }
dog1.sayName()   //luky
// 新增到全域性物件 在node環境中全域性物件是global,在瀏覽器執行環境中,全域性物件是window
Dog('lily', 3, 'black')
global.sayName()  //lily
//window.sayName() //lily  //在瀏覽器中執行才會有輸出結果

// call指標的實現示例:
// 在另一個物件的作用域中呼叫
// 新建一個物件
let objCall = new Object()
Dog.call(obj, '小七', 2, 'gold')
obj.sayName()  //小七
console.log(obj.color);  //gold

方法四 ---- 使用工廠函式創造物件

function createPerson(name, age, gender) {
    let person = new Object()
    // 給person例項新增屬性
    person.name = name
    person.age = age
    person.gender = gender
    person.sayName = function () {
        console.log(this.name);
    }
    return person
}
let person1 = createPerson('zhang', 18, 'male')
console.log(person1); // { name: 'zhang', age: 18, gender: 'male', sayName: [Function (anonymous)] }
person1.sayName()  //zhang

方法五 ---- 使用組合模式(建構函式模式和原型模式)建立物件

//建構函式中放私有屬性和方法
function Pig(name, age, hobby) {
    this.name = name
    this.age = age
    this.hobby = hobby
    this.friends = ['六尾','德華']
}
//在原型物件中存放公有屬性和方法   Person.prototype重寫後指向Object,不指向原來的Person
Person.prototype = {
    //讓constructor屬性重新指向Person
    constructor: Pig,
    sayName: function () {
        console.log(this.name);
    }
}
//建立物件例項
let p1 = new Pig('小香', 1, '蘋果')
let p2 = new Pig('小芳', 3, '炸雞');
console.log(p1); //Pig { name: '小香', age: 1, hobby: '蘋果', friends: [ '六尾', '德華' ] }
//改變其中一個例項
p1.friends.push('robin');
//例項之間的私有屬性互不影響
console.log(p1.friends);//[ '六尾', '德華', 'robin' ]
console.log(p2.friends);//[ '六尾', '德華' ]

相關文章