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

JavaScript对象 创建对象 继承

时间:2014-08-07 22:51:45      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   java   io   strong   ar   cti   

创建对象  --以下内容来自JavaScript高级程序设计

工厂模式

用函数来封装以特定接口创建对象的细节。

        function createPerson(name, age, job){
            var o = new Object();
            o.name = name;
            o.age = age;
            o.job = job;
            o.sayName = function(){
                alert(this.name);
            };    
            return o;
        }
        
        var person1 = createPerson("Nicholas", 29, "Software Engineer");
        var person2 = createPerson("Greg", 27, "Doctor");
        
        person1.sayName();   //"Nicholas"
        person2.sayName();   //"Greg"

构造函数
用来创建特定类型的对象

        function Person(name, age, job){
            this.name = name;
            this.age = age;
            this.job = job;
            this.sayName = function(){
                alert(this.name);
            };    
        }
        
        var person1 = new Person("Nicholas", 29, "Software Engineer");
        var person2 = new Person("Greg", 27, "Doctor");
        
        person1.sayName();   //"Nicholas"
        person2.sayName();   //"Greg"
        
        alert(person1 instanceof Object);  //true
        alert(person1 instanceof Person);  //true
        alert(person2 instanceof Object);  //true
        alert(person2 instanceof Person);  //true
        
        alert(person1.constructor == Person);  //true
        alert(person2.constructor == Person);  //true
        
        //不同实例的同名函数是不相等的,每个方法都要在每个实例上重新创建一次。
        alert(person1.sayName == person2.sayName);  //false 

 

        function Person(name, age, job){
            this.name = name;
            this.age = age;
            this.job = job;
            this.sayName = sayName;
        }
        
        //把函数定义转移到构造函数外部,作为全局函数,没有封装性
        function sayName(){
            alert(this.name);
        }
        
        var person1 = new Person("Nicholas", 29, "Software Engineer");
        var person2 = new Person("Greg", 27, "Doctor");
        
        person1.sayName();   //"Nicholas"
        person2.sayName();   //"Greg"
        
        alert(person1 instanceof Object);  //true
        alert(person1 instanceof Person);  //true
        alert(person2 instanceof Object);  //true
        alert(person2 instanceof Person);  //true
        
        alert(person1.constructor == Person);  //true
        alert(person2.constructor == Person);  //true
        
        alert(person1.sayName == person2.sayName);  //true   

 

JavaScript对象 创建对象 继承,布布扣,bubuko.com

JavaScript对象 创建对象 继承

标签:style   blog   color   java   io   strong   ar   cti   

原文地址:http://www.cnblogs.com/YuanSong/p/3898119.html

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