面向对象:一个对象下有多种属性和方法
一:创建对象
// 一:创建对象
// 缺点:产生大量代码
var box = new Object();
box.name = 'wang';
box.age = 18;
box.run = function(){
console.log(this.age);
}
var box2 = new Object();
box2.name = 'lin';
box2.age = 19;
box2.run = function(){
console.log(this.name);
}
box.run();
box2.run();
二.工厂模式
解决了大量重复代码,1.但存在内存消耗太大,2.函数识别问题
// 二.工厂模式
// 解决了大量重复代码,1.但存在内存消耗太大,2.函数识别问题
function createObject(name, age){
// console.log(name,age)
var box = new Object();
box.name = name;
box.age = age;
box.run = function(){
console.log(this.name)
console.log(this.age)
}
return box
}
var c = createObject('wang', 13);//执行
var d = createObject('lin', 19);//执行
c.run();
d.run();
三.构造函数法(加个new)
解决了函数识别问题,1.但消耗内存问题没有解决;2.this作用域的问题
// 三.构造函数法(加个new)
// 解决了函数识别问题,1.但消耗内存问题没有解决;2.this作用域的问题
function CreateObject(name, age){
// var box = new Object();//省略了
this.name = name;
this.age = age;
this.run = function(){
console.log(this.name)
console.log(this.age)
}
// return box//省略了
}
var son = new CreateObject('lalal', 13);//执行
var son1 = new CreateObject('caiji', 19);//执行
son.run();
son1.run();
四.混合方式。(构造函数+原型模式)1.加上new;2.原型
解决了消耗内存问题。当然它也可以解决this作用域等问题
// 1.构造函数里放属性
function CreatePeople(name, age){
// var box = new Object();//省略了
this.name = name;
this.age = age;
// return box//省略了
}
// 2.方法放外面
//构造函数名.原型.方法名
CreatePeople.prototype.show = function(){
console.log(this.name)
}
CreatePeople.prototype.showAge = function(){
console.log(this.age)
}
var a = new CreatePeople('lalal', 13);//执行
var b = new CreatePeople('caiji', 19);//执行
a.show();
b.showAge();