开发工具
Angular 1.4.8 和 lodash
问题
编辑
澄清我的问题:
- 创建一个对象(文章)
- 应用构造函数
- 然后导入第三个对象的属性,但是把它放在 proto 文件夹,这样我就不会得到大量的属性 在根
正如我所说,我的代码有效,但我问,因为我来自更结构化的语言背景,而且继承感觉脆弱和困惑,但也许那是 JS ES5 ... 6 看起来更好。
下面的代码有效,但由于我是 JS 的新手,我想知道是否有更好的方法来构建一个对象(“类”),我从传入的数据/键创建一个构造器,然后扩展我当前的proto 文件夹中的部分/文件夹中具有第三个对象属性的对象?构建构造并继承属性的 Extendable()
函数感觉很难看。
在下面的例子中:
- 我通过注入(inject)数据和 key 创建了一个文章实例。然后我
使用 _constructor 工厂为创建一个构造函数
文章模型
。 - 然后我使用 3rd 的属性扩展文章实例
object, model (Model Provider),但也想将它们放在
__proto__
文件夹中,并使用特定的键“Eloquent”。
例子:
Extendable
// Extendable constructor properties
__proto__: Extendable
Eloquent: Object
// 'Eloquent model' inherited properties
代码:
(function() {
'use strict';
_Constructor.$inject = [];
function _Constructor() {
function __constructor(data, keys) {
_.assign(this, _.pick(data, keys));
}
return __constructor;
}
ArticleModel.$inject = ['model', '_Constructor'];
function ArticleModel(model, _Constructor) {
function Extendable(data, keys) {
_Constructor.call(this, data, keys);
// This works but NOT pretty. Is there a cleaner or better way to decorate / inherit e.g. is there a ::__parent() method?
var decorate = Extendable.prototype['Eloquent'] = {};
// model is a the main model provider
_.assign(decorate, model);
}
Extendable.prototype = Object.create(_Constructor.prototype);
Extendable.prototype.constructor = Extendable;
var article = Extendable.prototype;
article.pleaseWork = function() {
return 'The JS gods are pleased! move forward 1 test!';
};
return Extendable;
}
angular.module('article', [
])
.factory('_Constructor', _Constructor)
.service('article', ArticleModel)
})();
最佳答案
我不完全理解您要在这里实现的目标。听起来您正在尝试创建新对象,这些对象也将从基础对象和可能从第三个对象继承属性。
假设您有一个基础对象:base = {foo: 1} 现在你有另一个对象: third = {third: 1} 现在我们要创建一个继承自 base 并具有 third 属性的对象。
var newGuyOnTheBlock = Object.create(base); //creates a new object from base and will have all properties from base
_.extend(newGuyOnTheBlock, third); // now it'll have properties from third and base
关于javascript - Angular 1.4.8/JS : create constructor and inherit properties into a 3rd object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34562561/