标签:java shel friend on() cti 自定义 turn function 产生
使用字面量方式创建多个对象时,会产生大量的重复代码。开发者在寻找创建多个对象方法的过程中,基本经历了一下集中方法:
工厂模式 > 构造函数模式 > 原型模式 > 构造函数与原型组合 > 寄生构造函数 > 稳妥构造函数模式
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;
}
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.ageName = sayName;
}
function sayName(){
alert(this.name);
}
function Person(){
}
Person.prototype.name = "xiong";
Person.prototype.age = "26";
Person.prototype.job = "FE";
Person.prototype.sayName = function(){
alert(this.name)
};
问题:当原型上包含引用类型的值得情况下,所有实例会共享该引用类型值。即任何一个实例修改该引用类型值,其他所有的实例也会反映出来。所以很少使用这种方式。
构造函数与原型混成的模式,是目前在ECMAScript中使用最广泛、认同度最高的一种创建自定义类型的方法。可以说是定义引用类型的默认模式。
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.ageName = sayName;
this.friends = ["Shelby","Court"];
}
// prototype 上共享方法
Person.prototype = {
constructor: Persion,
sayName: function(){
alert(this.name)
}
}
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.ageName = sayName;
this.friends = ["Shelby","Court"];
if(typeof this.sayName != "function"){
Person.prototype.sayName = function(){
alert(this.name);
}
}
}
function Person(name, age, job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.ageName = sayName;
o.friends = ["Shelby","Court"];
return o;
}
var person = new Person("fd",34,"FE");
function Person(name, age, job ){
var o = new Object();
o.sayName = function(){
alert(name)
}
return o;
}
var friend = new Person("t", 23, "fe");
friend.sayName();
标签:java shel friend on() cti 自定义 turn function 产生
原文地址:https://www.cnblogs.com/wanxiong/p/js-basic-Object-new.html