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

Ken*_*eth 5 javascript function-prototypes

我最近一直在试验javascript中的原型,我无法弄清楚为什么以下代码不起作用.我想做的是用参数n创建一个新的奶酪实例.

function food(n) {
    this.n=n;
}
function cheese(n) {
    alert(this.n);
}
cheese.prototype=new food;
new cheese('paramesian');
Run Code Online (Sandbox Code Playgroud)

CMS*_*CMS 9

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

你可以做几件事:

1.使用对象和新创建的context()在函数内部应用Food构造Cheese函数.argumentsthis

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

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

new Cheese('paramesian');
Run Code Online (Sandbox Code Playgroud)

2.在构造函数上重复Food构造函数logic(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');
Run Code Online (Sandbox Code Playgroud)

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');
Run Code Online (Sandbox Code Playgroud)

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'
Run Code Online (Sandbox Code Playgroud)