Javascript创建类型的几种方式 /*创建对象 *///logfunction trace(args) { console.log(args); }//1,工厂模式//对象不能被识别, 没办法通过instanceof识别具体对象trace("---------------工厂模式---------------");f
/* 创建对象 */ //log function trace(args) { console.log(args); } //1,工厂模式 //对象不能被识别, 没办法通过instanceof识别具体对象 trace("---------------工厂模式---------------"); function createPerson(name, age, job) { var o = new Object(); o.name = name; o.age = age; o.job = job; o.sayName = function () { trace(this.name); }; return o; } var person1 = createPerson("Kun", 18, "小混混"); var person2 = createPerson("test", 20, "战士"); person1.sayName(); //2. 构造函数模式 trace("---------------构造函数模式---------------"); function Person2(name, age, job) { this.name = name; this.age = age; this.job = job; this.sayName = function () { trace(this.name); }; } var person1 = new Person2("Kun1", 18, "小混混"); var person2 = new Person2("Kun2", 18, "小混混"); person1.sayName(); person2.sayName(); trace(person1 instanceof Person2); //3. 原型模式 console.log("---------------原型格式---------------"); function Person3() { } var __p = Person3.prototype; __p.name = "Kun"; __p.age = 19; __p.job = "吹水"; __p.sayName = function () { trace(this.name); }; __p.hasPrototypeProperty = function (name) { return !this.hasOwnProperty(name) && name in this; }; var person1 = new Person3(); var person2 = new Person3(); person1.name = "codekun"; // person1.sayName(); // person2.sayName(); // delete person1.name; // person1.sayName(); trace(person1.hasOwnProperty("age")); trace(person1.hasPrototypeProperty("age")); var a = Object.keys(person1); trace(a); //4.组合使用构造函数模式与和原型模式 function Person4(name, age, job) { this.name = name; this.age = age; this.job = job; this.friends = ["陈三","李四"]; } Person4.prototype = { constructor : Person4, sayName : function () { trace(this.name); } } //5.动态原型模式 function Person5(name, age, job) { this.name = name; this.age = age; this.job; if(typeof this.sayName != "function") { Person5.prototype.sayName = function () { trace(this.name); } } } //6.寄生构造函数模式 function Person6(name, age, job) { var o = new Object(); o.name = name; o.age = age; o.job = job; o.sayName = function () { trace(this.name); }; return o; }