首页 > 代码库 > JavaScript对象 创建对象 继承

JavaScript对象 创建对象 继承

创建对象  --以下内容来自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