一、js基础创建方式
① 有点:简单方便
② 缺点:无法量产
var students=[];
var s0 = {
name:"jj",
age:"18",
eat:function(){
console.log(this,name+"正在学习")
}
}
二、为了量产,利用函数来封装重复使用的代码 此模式可成为 “工厂模式创建对象”
- 优点:可以量产
- 缺点:通过工厂模式创建出来的对象,无法明确它所对应的类型
function createStudent(name,age){
var s = new Object();
s.name = name;
s.age = age;
s.eat = function(){
console.log(this,name+"正在学习")
};
return s
}
var s1 = createStudent("zjs","119");
console.log(s1);
var s2 = createStudent("zxc","120");
console.log(s2);
Ps :我们通过可以 instanceof 来判断对应的变量类型 typeof()返回的是数据类型
var arr = [1,2,3]
var result = arr instanceof Array
console.log(result) // 返回 true
var result = arr instanceof Object
console.log(result) //返回 true
var num = 123;
var result = arr instanceof Number
console.log(result) //返回 false
number string boolean 判断简单数据类型
如果使用 new Number()创建则为真
var a= new Number(123)
var result = a instanceof Number
console.log(result) //返回 true
三、通过 构造函数方式 创建对象
构造函数模式 借鉴了其他预言创建对象的方法 创建类
工厂模式无法检测创建出来的对象类型
类:同一类型事物的总称,包含的属性和方法都写到构造函数中
js默认没有类这个概念
通过构造函数模式,来模拟类 !!!!! 利用js this指向的问题
优点 明确了数据类型
弊端 共用的方法没有封装 占据内存
function Student(name,age){
this.name = name;
this.age = age;
this.eat = function(){
console.log(this,name+"学习")
}
}
var s3 = new Student("急急急",22)
var s4 = new Student("阿萨德",66)
console.log(s3)
console.log(s4)
// s3 s4 prototype 原型都是一样的 但是 存在了不同位置
console.log(s3.prototype == s4.prototype) // true
- 优点:明确了数据类型
- 缺点:共用的方法并没有封装 占用内存 由此产生了第四种创建方式
Ps:此方式是通过模拟“类”的方式 来创建对象的
此处的new 做了什么?
- 创建一个空对象
- 执行后面的构造函数,将函数的内容this指向空对象
- 在函数执行完成后,将创建的空对象返回给前方变量
四、创建构造函数过程中,将共有的方法嵌入到构造函数的原型里
function Student(name,age){
this.name = name;
this.age = age;
}
// 共用方法
Student.prototype.eta = function(){
console.log(this.name,"正在吃")
}
var s6 = new Student("我是谁",88);
var ss = new Student("你",99);
console.log(s6)
console.log(s6.__proto__ == Student.prototype)
s6.eta()
var ss = new Student("你",99);
Ps:嵌入到原型里的方法是共用的,无论是“谁”去调用修改它 其他再去调用 所使用的也是被修改过的 改变原型中的方法 使用 __proto__
ss.__proto__.eta = function(){
console.log(this.name,"不吃了")
}
s6.eta() // 我是谁 不吃了
ss.eta() // 你 不吃了
想要单独改变某一个 可以选择给它单独加一个属性
s6.eta = function(){
console.log(this.name,"正在吃")
}
s6.eta() // 我是谁 正在吃
console.log(s6)
var b1 = {
name:"wo",
eag:66
}
var b2 = b1;
b1.eag = 88;
console.log(b2.eag) //返回 88