JavaScript创建对象的多种方法

方法一----通过字面量创建

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); //[ '六尾', '德华' ]

    推荐阅读