工厂模式与自定义构造函数

工厂模式与自定义构造函数



先说下创建对象的三种方式
**1. 通过内置对象来创建**
var obj = new Object();
obj.name = 'hu';
obj.age = 12;



**2.通过字面量的方式来进行创建**
var obj = {
	name:'hu',
	age:12,
	sex:'男'
}\
console.log(obj.name);
console.log(obj.age);



**3.通过构造函数来进行创建对象**
function Person(name.age,sex){
	this.name = name;
	this.age = age;
	this.sex = sex;
	this.setName = function(){
		console.log(the name is 'name');
	}
}
var per = new Person('hu',12,'男');
console.log(per.name);
console.log(per.age);
per.setName();//进行调用方法

js创建对象的三种基本方式
工厂模式 自定义构造函数  原型模式
工厂模式
function person(name,age){
	var per = new Object();
	per.name = name;
	per.age = age;
	per.say = function(){
        alert(this.name);
    }   
       return per; 
	
}
自定义构造函数
function Person(name,age){
	this.name = name;
	this.age = age;
	this.sayHello = function(){
		console.log('this is sayHello ')
	}
}
var per = new Person('hu',22);

原型模式
function Person(name,age){
	this.name = name;
	this.age = age;
	
}
//方法全部写在原型当中,原型实现共享,节省内存空间
Person.prototype.eat = function(){
	console.log(' eat is bad');
}
Person.prototype.init = function(){
	console.log('the init is person');
}
//创建实例对象
var per = new Person('hu',22);
console.log(per.name);
console.log(per.age);
per.init();

猜你喜欢

转载自blog.csdn.net/weixin_42355871/article/details/83547287
今日推荐