构造函数创建对象

构造函数创建对象

function Dog(name,age){
    this.name = name;
    this.age = age;
    this.sayName = function(){
        return this.name;//每创建一个对象时,都会创建一个新函数
}
}
function sayHello(){
    return this.name;
}//把函数放在全局,可以避免重复创建函数,但封装性差
var d1 = new Dog('xiaoming',2);
console.log(d1.__proto__.constructor);//返回一个对象的构造函数
d1.sayHello();

原型模式创建对象

function Dog(){};
//在prototype中定义属性和方法,所有的实例对象都共享
Dog.prototype.name = 'xiaobai';
Dog.prototype.age = 2;
Dog.prototype.text = {
    t:'is dog',
} ;
Dog.prototype.sayHello = function(){
    return this.name;
}
var dog1 = new Dog();
Dog.text.t = 'is white dog';
console.log(dog1.text.t);//is white dog
dog1.sayHello();
dog1.name = 'xiaohei';
console.log(dog1.name);//xiaohei
console.log(dog1);//Dog {}

构造函数与原型链结合

function Dog(name,age){
    this.name = name;
    this.age = age;
    this.arr = [];//重复创建,不会影响
}
Dog.prototype.sayHello = function(){
    return this.name;
}
var d1 = new Dog('xiaoming',2);
console.log(d1);//{ name: 'xioaming', age: 2, arr: [] }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值