我试图封装一个javascript对象,并声明了一些原型函数。但是有一些错误。
这是我的代码:
const editor_theme = require('./editor-theme.js')
let defaultTheme = new editor_theme.Editor_Theme('{"titlebar_color": "f0f0f0", "background_color": "ffffff"}')
defaultTheme.setTitlebarColor('888888')
console.log(defaultTheme.getTitlebarColor())
//main.js
module.exports = {
Editor_Theme: function (data) {
var _themeData = JSON.parse(data)
var _titlebar_color = _themeData.titlebar_color
var _background_color = _themeData.background_color
const Func = function() { }
Func.prototype = {
getTitlebarColor : function () {
return _titlebar_color
},
getBackgroundColor : function () {
return _background_color
},
setTitlebarColor : function (titlebarColor) {
_titlebar_color = titlebarColor || _titlebar_color
}
}
Object.freeze(Func)
Object.freeze(Func.prototype)
return Func
}
}
//editor-theme.js
它是错误日志:
未捕获的TypeError:defaultTheme.setTitlebarColor不是函数
答案 0 :(得分:2)
您的构造函数现在返回另一个构造函数,而不是对象。而是返回该构造函数的实例:
// module.exports = {
let moduleExports = {
Editor_Theme: function(data) {
var _themeData = JSON.parse(data)
var _titlebar_color = _themeData.titlebar_color
var _background_color = _themeData.background_color
const Func = function() {}
Func.prototype = {
getTitlebarColor: function() {
return _titlebar_color
},
getBackgroundColor: function() {
return _background_color
},
setTitlebarColor: function(titlebarColor) {
_titlebar_color = titlebarColor || _titlebar_color
}
}
Object.freeze(Func)
Object.freeze(Func.prototype)
return new Func() //Instantiate constructor
}
}
// const editor_theme = require('./editor-theme.js')
const editor_theme = moduleExports
let defaultTheme = new editor_theme.Editor_Theme('{"titlebar_color": "f0f0f0", "background_color": "ffffff"}')
defaultTheme.setTitlebarColor('888888')
console.log(defaultTheme.getTitlebarColor())
或更妙的是,只需Object.create
一个带有自定义原型的对象:
// module.exports = {
let moduleExports = {
Editor_Theme: function(data) {
var _themeData = JSON.parse(data)
var _titlebar_color = _themeData.titlebar_color
var _background_color = _themeData.background_color
const prototype = {
getTitlebarColor: function() {
return _titlebar_color
},
getBackgroundColor: function() {
return _background_color
},
setTitlebarColor: function(titlebarColor) {
_titlebar_color = titlebarColor || _titlebar_color
}
}
Object.freeze(prototype)
return Object.create(prototype) //Object with custom prototype
}
}
// const editor_theme = require('./editor-theme.js')
const editor_theme = moduleExports
let defaultTheme = new editor_theme.Editor_Theme('{"titlebar_color": "f0f0f0", "background_color": "ffffff"}')
defaultTheme.setTitlebarColor('888888')
console.log(defaultTheme.getTitlebarColor())