你做错了什么
您将其设置为undefined
:它本身就是一个值。你根本不应该定义它来让它工作:
// base object
function Animal (nameArg, typeArg) {
if (nameArg) this.name = nameArg;
if (typeArg) this.type = typeArg;
// could be added to prototype, it's the same for each instance
this.sayHello = function () { console.log("Hello my name is " + this.name + " and I am an " + this.type); }; // don't use commas here, use the + operator instead
}
// Setting defaults
Animal.prototype.name = "Anonymous";
Animal.prototype.type = "Animal";
var cat = new Animal(); // passing no arguments to constructor
cat.sayHello(); // now gives correct result ("Hello my name is Anonymous and I am an Animal")
//instantiating an animal WITH argguments passed in
var lion = new Animal("Jimmy", "Lion"); // always worked
为什么会这样
实际上,设置为未定义的变量和从未定义的变量之间存在差异,这很有趣——这又是 JavaScript 的另一个常见怪癖。要区分未定义变量和未定义变量,请看以下示例:
var foo = { x: undefined };
console.log('x' in foo); // true, x has been defined as "undefined"
console.log('y' in foo); // false, foo.y has never been defined
JavaScript 中的参数默认为undefined
,类似于最初定义变量时没有为其设置值或显式设置为undefined
:
function test(arg)
{ console.log(arg); // undefined
console.log(doesNotExist); // ReferenceError: doesNotExist is not defined
}
test(); // run and see
通过分配给它,JavaScript 会记录它被分配的内容,因此不会查找原型链来查看属性是否存在(参考)。