一、面向对象的创建方式
对象-----属性、方法
1.普通方式
var obj=new Object()
//添加对象的属性
obj.a=12
obj.b="hello"
//添加对象方法
obj.m1=function(){
// console.log(this);//指向obj
alert("m1....."+this.a)
}
obj.m2=function(){alert("m2.....")}
// console.log(obj)
// 调用对象
console.log(obj.a)
obj.m1()
2.直接量方式
{key:value,key:value....}
var obj={
a:"hello",
b:1,
m1:function (){alert("hello"+this.a)},
m2:function(){alert("m2.....")}
}
obj.m1()
3.函数对象方法
function f1(a,b){return a+b}
转换:
var f1=new Function('a','b','return a+b')
var obj =new Function('this.a=12,this.b="hello",this.m1=function(){alert("m1...")},this.m2=function(){alert("m2...")}')
//调用
var o1=new obj()
console.log(o1.a);
o1.m2()
4.构造函数方式
function Person(){
this.name="zs"
this.age=23
this.say=function(){alert("hello")}
this.eat=function(){alert("huoguo")}
}
//创建实例
var hyw1=new Person()
hyw1.age
hyw1.eat()
var hyw2=new Person()
hyw2.age
hyw2.eat()
5.原型方式创建
function Person(){
Person.prototype.name="zs"
Person.prototype.age=23
Person.prototype.say=function(){
alert("hello...")
}
Person.prototype.eat=function(){
alert("huoguo...")
}
}
//创建实例
var p1=new Person()
p1.age
p1.eat()