一. js中 创建对象
//好处:简单
//坏处:创建过程太过麻烦,尤其创建相同对象时
var s1={
name:"王一",
age:18,
eat:function(){
console.log(this.name+"正在吃")
}
}
s1.eat()
console.log(s1)
二.工厂模式 创建对象
//好处:可以快速创建想同类型对象
//坏处:类型都是object,无法明确对应实例类型
function createStudent(name,age){
var obj=new Object()
obj.name=name
obj.age=age
obj.eat=function(){
console.log(this.name+"正在吃")
}
return obj
}
var s1=createStudent("王一",12)
console.log(s1)
// instanceof 用于判断对应的数据类型 如果是 简单数据类型 Number string ,boolean 必须通过 原型方式创建,才会返回T
//A instanceof B A变量是否为B类型 返回 true或者false
//typeof() 返回对应的变量类型
例 var str=new String("hello world")
var r1=str instanceof String
console.log(r1)
三.构造函数 创建对象
//好处:解决了工厂问题弊端,可以简单对应的变量类型
//坏处: 同样的方法会开辟不同的内部,造成大量的内存消耗
function Student(name,age){
this.name=name
this.age=age
this.eat=function(){
console.log(this.name+'正在吃')
}
}
var s1=new Student("王一",21)
var s2=new Student("王二",19)
console.log(s1.__proto__==s2.__proto__)
console.log(s2.__proto__)
//new 做了什么?
//1.创建一个空对象 {}
//2.将构造函数中的this指向空对象
//3.将对象返回出来
//万物皆对象
四.原型 创建对象
//原型模式:将所有的共有的方法或者属性,绑定到构造函数的原型上 (最优)
//将共有的方法,放入构造函数的原型
//prototype是原型对象
function Student(name,age){
this.name=name
this.age=age
}
Student.prototype.eat=function(){
console.log(this.name+'正在吃')
}
Student.prototype.show=function(){
console.log(this.name)
}
var s1=new Student("王一",21)
s1.__proto__.he=function(){
console.log(this.name+"正在喝")
}
s1.he()
var s2=new Student("王二",19)
s2.he()
s1.eat()
s2.eat()
s1.show()
console.log(s1.eat==s2.eat)
console.log(s2)
console.log(s1.__proto__==Student.prototype)
//通过同一个类(构造函数)创建出来的对象,原型是相同的
//__proto__ 当前对象的原型 ==构造函数中原型 prototype
//将共有的方法 放入原型中,实现一个方法,多次使用了
console.log(s1.__proto__==s2.__proto__)