我正在使用jQuery / JavaScript创建一个网站,我得到的问题是:当我创建aMenu的几个实例时,我在一个单独的文件中创建的一个对象 - 它似乎用每个选项更新每个选项对象,尽管是他们自己的变量。
我创建aMenu对象的JavaScript:
// Drawer item, animates via CSS - no need to animate using jQuery
var drawerOptions = {
animate: false,
toggle_element: '#parent',
toggle_attribute: 'data-opened',
default_toggled: false,
toggle_after_animation: false
}
var Drawer = new aMenu(drawerOptions);
// LargeDrawer item
var largeDrawerOptions = {
animate: false,
toggle_element: '#parent',
toggle_attribute: 'data-opened',
default_toggled: false,
toggle_after_animation: false
}
var LargeDrawer = new aMenu(largeDrawerOptions);
// Search item
var searchbarOptions = {
animate: true,
toggle_element: '.search_nav_drop',
toggle_attribute: 'data-opened',
default_toggled: false,
toggle_after_animation: true,
animation: 'slide'
}
var NSearchBar = new aMenu(searchbarOptions);
aMenu对象:
function aMenu(options){
// Run our init if we have one.
this.options.onInit(this);
// Intertwine our current default options and whats being passed in.
// Same as $.extend
this.options = intertwine(this.options, options);
// Determine default toggling.
this.toggled = this.isToggled();
}
// Default options
aMenu.prototype.options = {
animate: true, // If we are animating this menu
animation: 'slide', // Animation types: none|fade|slide|custom
speed: 500, // Animation speed
easing: 'linear', // Easing into the animation types: linear|swing|_default
stop_event: false, // If the stop event is used in this case
toggle_element: '', // This element keeps track of being toggled in HTML. Leave blank or 'none' for keeping track in JavaScript
toggle_attribute: '', // Attribute that get toggled (true/false). Leave blank if toggle_element is blank or 'none'
default_toggled: true, // The default selection if we are toggled or not (only used if no toggle_element)
throw_errors: true, // If you want errors to be thrown for problem code.
toggle_after_animation: true, // If you want the menu to toggled after the animation is completed.
onToggle: function() {return false;}, // Function gets trigger when toggled
onInit: function() {return false;}, // Function gets trigger at initialization
onHide: function() {return false;}, // Function gets triggered when inactivated
onShow: function() {return false;}, // Function gets triggered when activated
onShowAnimationCompleted: function() {return false;}, // Function gets triggered after animation completes on show
onHideAnimationCompleted: function() {return false;} // Function get trigger after animation completes on hide
}
只是要指定,对象Drawer将具有与NSearchBar相同的选项,并且Drawer将完全被破坏。
不确定这是原型设计的问题,还是我完全遗漏的问题。感谢任何帮助,谢谢!
答案 0 :(得分:0)
this.options
最初引用aMenu.prototype.options
intertwine
(如果它与$.extend
相同)扩展并返回目标:
请记住,目标对象(第一个参数)将被修改,并且也将从$ .extend()返回。
所有this.options
的实例aMenu
都相同。
你需要写:
this.options = $.extend({}, this.options, options)
这会将this.options
的属性(最初引用aMenu.prototype.options
)复制到新的对象,然后复制options
的属性并返回分配给{{1}的新对象}}
如果它与this.options
一样有效,取决于你如何实现它。