js对象实例化方式

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Object</title>
</head>
<body>
<h1>创建对象常见的三种方式</h1>
</body>
<script>
    window.onload=function(){
        //工厂模式
        function oj(){
            var lio=new Object();
            lio.name='lio';
            lio.attr='男';
            lio.hobby=function(){
                var li=document.createElement("p");
                var txt=document.createTextNode("三妹");
                li.appendChild(txt);
                document.body.appendChild(li);
            };
            return lio;
        }
        var person=oj();
        //alert(person.name);
 
        //构造函数模式
        function oj2(name,age){
            this.name=name;
            this.age=age;
            this.hobby=function(){
                var li=document.createElement("p");
                var txt=document.createTextNode("三妹");
                li.appendChild(txt);
                document.body.appendChild(li);
            }
        }
        var person2=new oj2('三妹',123);
        person2.hobby();
        alert(person2.name);
 
        //原型模式
        function oj3(){
            //this.name='lio';
        }
        oj3.prototype.name='lio';
        oj3.prototype.love= function (name) {
            alert("爱"+name);
        };
        var person3=new oj3();
        //检测是在实例中还是在原型中
        alert(person3.hasOwnProperty("name"));
        alert(person3.hasOwnProperty("rename"));
        person3.love('三妹');
 
        //混合模式
        function oj4(age) {
            this.age=age;
            this.rename='aaaa';
        };
        oj4.prototype={
            constructor:oj4,
            name:'lio',
            age:123,
            love: function (name) {
                alert(name+"爱三妹");
            }
        };
        var person4=new oj4(18);
        alert(person4.hasOwnProperty("age"));//true
        person4.love('lio');
 
    }
</script>
</html>

来源:https://blog.csdn.net/theowl/article/details/47361175

转载于:https://www.cnblogs.com/fengyouqi/p/9555420.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值