Passing parameters to a prototyped function in javascript

こ雲淡風輕ζ 提交于 2019-12-22 07:37:48

问题


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');

回答1:


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.

You can do a couple of things:

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 . 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 . 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 . Yet another option, prototypal inheritance:

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



回答2:


Seems like you just want to understand how prototype chaining works in JavaScript. The following is an excellent, simple and well explained tutorial http://www.herongyang.com/JavaScript/Inheritance-from-Constructor-Prototype-Object.html




回答3:


Edit, This is apparently not prototypical inheritance (see comments), but it does seem to work for this particular purpose.

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

    alert(this.n);
}

new cheese('paramesian');


来源:https://stackoverflow.com/questions/1814201/passing-parameters-to-a-prototyped-function-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!