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
函数。
我该怎么做?
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中极其常见的惯例是不将它们大写。所以box
和box2
,而不是Box
和Box2
。