创建对象的方式

一、创建对象的方式

1、字面量创建对象
2、new Object()创建对象
3、工厂函数
4、构造函数

二、使用方法

1.字面量创建对象

代码如下(示例):

var car = {
        color: '白色',
        price: 10,
        code: '冀A9999',
        logo: '&',
        flag: true,
        run: function () {
            console.log(this);
        },
        play: function () {
            console.log('带朋友');
        }
    }
console.log(car.price);
console.log(car.code);
car.run()

2.new Object()创建对象

代码如下(示例):

var person = new Object()
    person.name = 'zs'
    person.age = 18
    person.sex = '男'
    person.eat = function () {
       console.log('会吃');
    }
console.log(person);
console.log(typeof person);
console.log(person.name);
person.eat()

3.工厂函数

代码如下(示例):

 function createPerson(name1, age, sex, eat) {
        var person = new Object()
        person.name = name1
        person.age = age
        person.sex = sex
        person.eat = eat
        return person
    }
var person = createPerson('zs', 18, '男', function () { console.log('会吃'); })
var person_1 = createPerson('ls', 20, '女', function () { console.log('真会吃'); })
var person_2 = createPerson('ww', 30, '男', function () { console.log('非常会吃'); })
console.log(person);
console.log(person_1);
console.log(person_2);

4.构造函数

代码如下(示例):

function Person(name, age, sex, play) {
        this.name = name
        this.age = age
        this.sex = sex
        this.play = play
    }
var person = new Person('zs', 20, '男', function () { console.log('玩游戏'); })
var person_1 = new Person('zs1', 20, '男', function () { console.log('玩游戏'); })
console.log(person);
console.log(person_1);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值