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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM