class Classname {
constructor(args) {
// code
}
// this method is added to Classname.prototype
function_name(argument) {
// body...
}
//how to add objects similarly to prototype
}
有没有办法将对象添加到Classname.prototype?
答案 0 :(得分:0)
您可以使用getter和setter在类体内的原型上定义属性。但这有点冗长。
例如。
const obj = {
name: 'Shared'
}
class A {
get a() {
return obj
}
}
const a1 = new A
console.log(A.prototype.hasOwnProperty('a'))
console.log(a1.hasOwnProperty('a'))
console.log(a1.a)

答案 1 :(得分:-1)
Classname.prototype.myObject = {};
或者
Classname.prototype.myObject = Object.assign({ foo: 'bar'}, { bar: 'baz' }, anotherObject)
例如
const User = function() {};
User.prototype.info = Object.assign({ foo: 'bar' }, { bar: 'baz' });
const bob = new User();
bob.info; // => { foo: 'bar', bar: 'baz' }