zoukankan      html  css  js  c++  java
  • 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

    工欲善其事 必先利其器
  • 相关阅读:
    POJ 1981 最大点覆盖问题(极角排序)
    POJ 1286 Pólya定理
    POJ 1830 高斯消元
    HDU 3364 高斯消元
    Educational Codeforces Round 42D. Merge Equals(STL)
    ZOJ 3955:Saddle Point(思维)
    POJ 3301:Texas Trip(计算几何+三分)
    SCUT 125 :笔芯回文(DP)
    ZOJ 3953:Intervals(优先队列+思维)
    Codeforces Gym101097I:Sticks (思维)
  • 原文地址:https://www.cnblogs.com/fengyouqi/p/9555420.html
Copyright © 2011-2022 走看看