面向对象的五种创建方式

一、面向对象的创建方式
对象-----属性、方法
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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值