将参数传递给javascript中的原型函数 [英] Passing parameters to a prototyped function in javascript
问题描述
我最近一直在尝试使用javascript进行原型制作,但我不知道为什么以下代码不起作用.我想做的是使用参数n创建一个Cheese的新实例.
I've been recently experimenting with prototyping in javascript and I can't figure out why the following code doesn't work. What I would like to do is create a new instance of cheese with parameter n.
function food(n) {
this.n=n;
}
function cheese(n) {
alert(this.n);
}
cheese.prototype=new food;
new cheese('paramesian');
推荐答案
您正在创建一个新的Cheese
实例,并且从未使用或分配参数n
或将其分配给Cheese
实例变量this.n
,因为该逻辑仅在Food
构造函数上使用.
You are creating a new Cheese
instance, and the argument n
is never used or assigned to the Cheese
instance variable this.n
, because that logic is only used on the Food
constructor.
您可以做几件事:
1. 应用 Cheese
函数内部的Food
构造函数,并使用arguments
对象和新创建的上下文(this
).
1 . Apply the Food
constructor inside the Cheese
function, using the arguments
object and the newly created context (this
).
function Food(n) {
this.n=n;
}
function Cheese(n) {
Food.apply (this, arguments);
alert(this.n);
}
new Cheese('paramesian');
2.在Cheese
构造函数上重复Food
构造函数逻辑(this.n = n
):
2 . Repeat the Food
constructor logic (this.n = n
) on the Cheese
constructor function:
function Food(n) {
this.n=n;
}
function Cheese(n) {
this.n = n;
alert(this.n);
}
Cheese.prototype = new Food();
new Cheese('paramesian');
3.使用另一种技术,例如电源构造器:
3 . Use another technique, like power constructors:
function food (n) {
var instance = {};
instance.n = n;
return instance;
}
function cheese (n) {
var instance = food(n);
alert(instance.n);
return instance;
}
cheese('parmesian');
cheese('gouda');
4.另一个选择,原型继承:
// helper function
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F () {}
F.prototype = o;
return new F();
};
}
var food = {
n: "base food",
showName : function () { alert(this.n); }
};
var cheese1 = Object.create(food);
cheese1.n = 'parmesian';
cheese1.showName(); // method exists only in 'food'
这篇关于将参数传递给javascript中的原型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!