function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Shelby", "Court"];
this.sayName = function() {
alert("hi");
};
}if (typeof Person.sayName !== "function") {
Person.prototype = {
constructor: Person,
sayName: function() {
alert(this.name);
}
};
}
else {
Person.sayName();
}var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 29, "Doctor");
alert(person1.sayName());
alert(person2.sayName());我这个程序输出的是
hi
undefined
hi
undefined我的意图是if (typeof Person.sayName !== "function") {
Person.prototype = {
constructor: Person,
sayName: function() {
alert(this.name);
}
};
}
else {
Person.sayName();
}sayName不是函数(即不存在)的话就原型设计模式创建sayName(),否则(即存在又是函数类型)的话就调用现成的sayName(),怎么会输出有undefined?javascript设计模式functionconstructor