var CreateTest = function CreateTest(name) {
this.name = name
this.roll = () => ['simple', 'hard'][Math.round(Math.random())]
}
CreateTest.prototype.renameObj = function () {
return {
rename: () => {
return this.name = `${this.roll()} ${this.name}`
}
}
}
var test = new CreateTest('js test')
console.log(test.renameObj().rename())
мои 5 копеек %) |
Цитата:
примерно так
function CreateTest(params) {
this.name = params.name;
this._calcFunc = params.calcFunc;
}
CreateTest.prototype = {
constructor: CreateTest,
move: function() {
var calcResult = this._calcFunc();
// ...
}
};
var test = new CreateTest({
name: '...',
calcFunc: function() { return 2 + 2; }
});
test.move();
|
SuperZen, все бы хорошо, только надо передавать объект, а не функцию)
Alexandroppolus, надо передавать в функцию объект, чтобы он записывался в конструктор. Aetae, Ваша реализация очень хороша, я немного подкорректировал ее:
function CreateTest(name) {
this.name = name;
this.roll = () => ["simple", "hard"][Math.round(Math.random())];
}
function bindedAppend(parent, name, child) {
Object.defineProperty(parent.prototype, name, {
configurable: true,
enumerable: true,
get: function() {
return this[name] = new Proxy(this, {
get: (p, key) => key in child ? child[key] : this[key],
set: (p, key, val) => this[key] = val
})
}
});
};
bindedAppend(CreateTest, 'renameObj', {
value : 7,
rename: function() {
return this.name = `${this.roll()} ${this.name}`;
}
});
let test3 = new CreateTest("js test");
test3.renameObj.rename();
console.log(test3.name, test3.renameObj.value);
Придумаю потом, как объявить bindedAppend в конструкторе, будет совсем конфетка) |
| Часовой пояс GMT +3, время: 09:40. |