繁体   English   中英

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

[英]Passing parameters to a prototyped function in javascript

我最近一直在试验javascript中的原型,我无法弄清楚为什么以下代码不起作用。 我想做的是用参数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构造函数。

你可以做几件事:

1。 使用arguments对象和新创建的上下文( this )在Cheese函数中应用 Food构造函数。

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 ):

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

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

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

3。 使用另一种技术,如电源构造器

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中是如何工作的。 以下是一本优秀,简单且解释良好的教程http://www.herongyang.com/JavaScript/Inheritance-from-Constructor-Prototype-Object.html

编辑 ,这显然不是原型继承(见注释),但它确实似乎适用于这个特定的目的。

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

    alert(this.n);
}

new cheese('paramesian');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM