首先,让我们澄清一下原型与构造函数不是一回事。你展示的是一个构造函数。此函数将用于构造符合您创建的接口的新对象,但它也会从底层对象继承属性——该对象就是原型。
// This is your constructor function that takes arguments that help
// it construct the instance properties:
var Dog = function(name, age, color){
// These are the instance properties
this.name = name;
this.age = age;
this.color = color;
};
// And, here you are constructing a new instance of Dog
var pitBull = new Dog('Rocky', 5, 'black');
“我想像这样(通过编码)向它添加一个名为 type 的新参数”
var Dog = function(name, age, color, type){
// code goes here.. };
在构造函数创建后更改其基本参数结构确实不是正确的方法。您应该做的是使用新的构造函数创建一个新的子类型,并让新类型从旧类型继承。新类型将采用所有 4 个参数,但它只会设置最新的一个,并将其他 3 个向下传递给它所继承的基础对象。
“同时我想添加一个具有确切名称的新属性”
没问题:
// Make new constructor function
function BetterDog(name, age, color, type){
this.type = type; // New property based on new parameter value
// Now pass the original 3 parameters to the prototype
// and let that object will handle the arguments as normal
Dog.prototype.constructor.call(this, name, age, color);
}
// Now, we'll set this new object to inherit from the earlier one by setting
// it's prototype to a new instance of a Dog. A new BetterDog is now going
// to inherit all the properties of Dog
BetterDog.prototype = new Dog();
// But, one problem here is that when we try to make a new instance of
// BetterDog, the Dog constructor function will be called. This happens
// because we switched the prototype. We can fix that like this:
BetterDog.constructor = BetterDog;
// Finally, we can construct a new BetterDog with all 4 parameters:
var pitBull = new BetterDog('Rocky', 5, 'black', 'PitBull');
整件事在一起:
// This is your constructor function that takes arguments that help
// it construct the instance properties:
var Dog = function(name, age, color){
// These are the instance properties
this.name = name;
this.age = age;
this.color = color;
};
// Make new constructor function
function BetterDog(name, age, color, type){
this.type = type;
// Now pass the original 3 parameters to the prototype
// and let that object will handle the arguments as normal
Dog.prototype.constructor.call(this, name, age, color);
}
// Now, we'll set this new object to inherit from the earlier one by setting
// it's prototype to a new instance of a Dog. A new BetterDog is now going
// to inherit all the properties of Dog
BetterDog.prototype = new Dog();
// But, one problem here is that when we try to make a new instance of
// BetterDog, the Dog constructor function will be called. This happens
// because we switched the prototype. We can fix that like this:
BetterDog.constructor = BetterDog;
// Finally, we can construct a new BetterDog with all 4 parameters:
var pitBull = new BetterDog('Rocky', 5, 'black', 'PitBull');
// Test:
console.log(pitBull.name);
console.log(pitBull.age);
console.log(pitBull.color);
console.log(pitBull.type);