zoukankan      html  css  js  c++  java
  • JavaScript创建对象

     1 // 工厂模式
     2 function createPerson(name, age){
     3     var o = new Object();
     4     o.name = name;
     5     o.age = age;
     6     o.show = function(){
     7         alert("hello s");
     8     };
     9     return o;
    10 }
    11 var person = createPerson("zhangsan", "22");
    12 person.show(); 
    hello s


     1 // 构造函数模式
     2 function Person(name,age){
     3     this.name = name;
     4     this.age = age;
     5     this.show = function(){
     6         alert("hello");
     7     }
     8 }
     9 var person = new Person("zhangsan", "20");
    10 person.show();
    hello


    1 // 原型模式
    2 function Person(){
    3 }
    4 Person.prototype.name = "kuikui";
    5 var person = new Person();
    6 alert(person.name);
    kuikui


     1 // 组合构造原型
     2 function Person(name,age){
     3     this.name = name;
     4     this.age = age;
     5     this.show = function(){
     6         alert("hello");
     7     }
     8 }
     9 Person.prototype = {
    10     constructor :Person,
    11     name : "kuikui",
    12     say : function(){
    13         alert("say me");
    14     }
    15 }
    16 var person1 = new Person("aa","23");
    17 person1.say();
    18 alert(person1.name);//构造优先原型 aa
    say me
    aa


     1 // 动态原型
     2 function Person(name, age){
     3     this.name = age;
     4     this.age = age;
     5     if(typeof this.show != "function"){
     6         this.show = function(){
     7             alert("构造 show");
     8         }
     9     }
    10     this.test = function(){
    11         alert("构造 test");
    12     }
    13 }
    14 Person.prototype = {
    15     show : function(){
    16         alert("原型 show")
    17     }
    18 }
    19 var person = new Person();
    20 var person1 = new Person();
    21 person.show();
    22 person1.test();
    23 //alert(Person.prototype.show); 
    原型 show
    构造 test


  • 相关阅读:
    SQL 查询优化
    win10鼠标右键菜单在左边,怎么改回右边
    Ansible 命令
    CSV模块
    Python 常用模块
    Ansible 常用模块
    Ansible 动态配置文件
    Cluster Health
    Elasticsearch Python API
    grok常用表达式
  • 原文地址:https://www.cnblogs.com/kkcodin/p/5412029.html
Copyright © 2011-2022 走看看