构造函数创建对象
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: [] }