码迷,mamicode.com
首页 > 编程语言 > 详细

javascript原型模式发展历程

时间:2020-01-16 12:41:13      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:pre   div   java   log   col   传递参数   this   console   his   

// 工厂模式

function Person(name,age){
            var o = new Object();
            o.name=name;
            o.age=age;
            o.sayName=function(){
                alert(o.name)
            }
            return o
        }

        var o1=Person(‘lele‘,5)
        
        var o2=Person(‘mama‘,31)

 

// 构造函数模式(能够标识对象属于哪一种类型,但是函数没有复用)

function Person(name,age){
            this.name=name;
            this.age=age;
            this.sayName=function(){
                alert(this.name)
            }
        }

        var o3=new Person(‘lele‘,5)
        console.log(o3)
        console.log(o3.constructor==Person)
        var o4=new Person(‘mama‘,31)
        console.log(o3.sayName==o4.sayName)

// 原型模式(不能传递初始化参数,包含了引用类型的共享)

function A(){}
        A.prototype.name=‘lele‘
        A.prototype.age=5
        A.prototype.sayName=function(){
            alert(this.name)
        }
        var o5 = new A();
        var o6 = new A();
        console.log(o5.sayName==o6.sayName)

// 组合是用构造函数模式和原型模式(能够传递参数,封装性不好,构造函数独立于)

 function B(name,age){
            this.name=name;
            this.age=age;
        }
        B.prototype.sayName=function(){
            alert(this.anme)
        }

        var o7=new B(‘lele‘,5)

// 动态原型模式

function C(name,age){
            this.name=name;
            this.age=age;
            if(typeof this.sayName != ‘function‘){
                C.prototype.sayName=function(){
                    alert(this.name)
                }
            }
        }
        var o8=new C(‘lele‘,6)

// class

javascript原型模式发展历程

标签:pre   div   java   log   col   传递参数   this   console   his   

原文地址:https://www.cnblogs.com/zhuMother/p/12200480.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!