如何将嵌套地图假设为原型?

问题描述 投票:1回答:1

const Box = {
  pick: function(...fruits) {
    this.fruits = "You've picked the fruits " + fruits;
  $('span[data-count]').text(this.fruits);
  }
}
var Box2 = Object.create(Box);
Box2.prototype.newMethod = function() {
  $('span[data-count]').text(this.fruits);
}
Box2.pick('Apple'); // Prototype?
Box.pick('Orange', 'Mango', 'Blueberry'); // Original
* {
  background-color: lightblue;
}
span {
  font-size: 2rem;
  font-family: 'Helvetica';
}
<span data-count></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

https://codepen.io/o22/pen/bZVWOJ

我坚持使用pick属性获取const Box内部的函数prototype

假设pick通过Box2直接工作正常。但是当我在代码中放入Box2.prototype.newMethod时,浏览器会触发错误。

我的目标是使用prototype属性来制作新方法并访问pick函数。

我该怎么做?

javascript html data-structures struct prototype
1个回答
1
投票

prototype属性特定于构造函数,它不是对象本身的原型。 (如果你想获得对象的原型,你可以使用Object.getPrototypeOf [你也可以看到使用不推荐的__proto__访问器属性的代码;不要在新代码中使用它。)

你的Box2不是构造函数,它只是一个对象。因此,如果要添加新方法,只需直接执行:

const Box = {
  pick: function(...fruits) {
    this.fruits = "You've picked the fruits " + fruits;
  $('span[data-count]').text(this.fruits);
  }
}
var Box2 = Object.create(Box);
Box2.newMethod = function() {
//  ^---- no .prototype here *********************************
  $('span[data-count]').text(this.fruits);
}
Box2.pick('Apple'); // Prototype?
Box.pick('Orange', 'Mango', 'Blueberry'); // Original

Box2将有自己的newMethod,并将从其原型(pick)继承Box

更简单的例子:

const a = {
  method1() {
    console.log("this is method1");
  }
};
const b = Object.create(a);
b.method2 = function() {
  console.log("this is method2");
};

b.method1();
b.method2();

作为一个小改进,当使用特定原型和一些想要添加的方法定义对象时,Object.assign非常方便:

const a = {
  method1() {
    console.log("this is method1");
  }
};
const b = Object.assign(Object.create(a), {
  method2() {
    console.log("this is method2");
  }
});

b.method1();
b.method2();

由于这些不是构造函数,因此JavaScript中极其常见的惯例是不将它们大写。所以boxbox2,而不是BoxBox2

© www.soinside.com 2019 - 2024. All rights reserved.