在javascript中将参数传递给原型函数

时间:2009-11-29 00:03:46

标签: javascript function-prototypes

我最近一直在尝试使用javascript进行原型设计,但我无法弄清楚为什么以下代码不起作用。我想做的是用参数n。

创建一个新的奶酪实例
function food(n) {
    this.n=n;
}
function cheese(n) {
    alert(this.n);
}
cheese.prototype=new food;
new cheese('paramesian');

3 个答案:

答案 0 :(得分:9)

您正在创建新的Cheese实例,并且永远不会使用或将参数n分配给Cheese实例变量this.n,因为该逻辑仅用于Food构造函数。

你可以做几件事:

1。使用Food对象和新创建的上下文(Cheesearguments函数内的this构造函数。{/ 3>

function Food(n) {
    this.n=n;
}

function Cheese(n) {
    Food.apply (this, arguments);
    alert(this.n);
}

new Cheese('paramesian');

2。在Food构造函数上重复this.n = n构造函数逻辑(Cheese):

function Food(n) {
    this.n=n;
}

function Cheese(n) {
    this.n = n;
    alert(this.n);
}

Cheese.prototype = new Food();
new Cheese('paramesian');

3。使用其他技术,例如Apply

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。还有另一种选择,power constructors

// 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'

答案 1 :(得分:0)

好像你只想了解原型链在JavaScript中是如何工作的。以下是一个优秀,简单且解释良好的教程 http://www.herongyang.com/JavaScript/Inheritance-from-Constructor-Prototype-Object.html

答案 2 :(得分:-1)

编辑,这显然不是原型继承(请参阅评论),但它似乎确实适用于此特定用途。

function food(n) {
    this.n=n;
}
function cheese(n) {
    this.prototype = food;
    this.prototype(n);

    alert(this.n);
}

new cheese('paramesian');
相关问题