(1)var obj={} obj.name=”simple” obj.age=18
(2)var obj=new Object()
(3)var obj={name:”simple”,age:18}
前面这三种方式存在两个个问题就是对象中的方法不能共享、每个方法都是独立的。而是代码冗余
(4) 使用工厂模式创建对象->用函数创建一个对象
function createObject(name)
{
var obj=new Object();
obj.name=name;
obj.sayHello=function(name)
{
console.log(`hello -${this.name}`);
}
return obj
}
var s=createObject("simple")
var m=createObject("baby")
s.sayHello();//hello -simple
m.sayHello();//hello -baby
/*此时的方法依然不是共享的,只是去除了代码的冗余问题*/
(5)通过构造函数创建对象,构造函数的首字母大写,普通函数的首字母小写
function Createobj(name)
{
this.name=name;
this.sayHello=function(){
console.log(`hello -${this.name}`)
}
}
var p1=new Createobj('simpe')
var p2=new Createobj('baby')
p1.constructor===p2.constructor
(6)通过原型的方式创建对象
function Animal(){}
alert(Animal.prototype.constructor==Animal);//true
function Createobj(){}
Createobj.prototype.name="simple";
Createobj.sayHello=function(){
console.log(`hello -${this.name}`)
}
var s1=new Createobj()
var s2=new Createobj()
s1.name="dog"
s1.sayHello()//hello - dog
/**首先在对象中寻找有无此属性,如果无就去对象的prototype中去寻找*/
s2.sayHello()//hello -simple
(7)原型+构造函数
<script>
'use strict';
function Animal(name){
this.name = name;
this.friends = ['dog','cat'];
}
Animal.prototype.sayName = function(){
alert(this.name);
};
var a1 = new Animal('d');
var a2 = new Animal('c');
a1.friends.push('snake');
alert(a1.friends);//[dog,cat,snake]
alert(a2.friends);//[dog,cat]
</script>