Javascript 原型取决于全局变量(如果该变量发生变化怎么办)
我正在构建一个JS原型函数,它使用的一个值基于一个名为“viewport”的全局对象。但是,如果该对象的值将发生变化;原型的值将不再准确 确保值始终相等的最佳或最有效的方法是什么 获取视口值:Javascript 原型取决于全局变量(如果该变量发生变化怎么办),javascript,jquery,prototype,Javascript,Jquery,Prototype,我正在构建一个JS原型函数,它使用的一个值基于一个名为“viewport”的全局对象。但是,如果该对象的值将发生变化;原型的值将不再准确 确保值始终相等的最佳或最有效的方法是什么 获取视口值: var viewport = { width: undefined } function initViewport($window){ viewport.width = $window.width(); } $(document).ready(function(
var viewport = {
width: undefined
}
function initViewport($window){
viewport.width = $window.width();
}
$(document).ready(function(){
initViewport($(window));
});
$(window).resize(function(){
initViewport($(window));
});
// Slider it's width is depending the viewport width
function Slider(){
this.width = viewport.width;
}
Slider.prototype.slide = function(){
console.log(this.width);
}
var slider = new Slider();
slider.slide();
创建原型:
var viewport = {
width: undefined
}
function initViewport($window){
viewport.width = $window.width();
}
$(document).ready(function(){
initViewport($(window));
});
$(window).resize(function(){
initViewport($(window));
});
// Slider it's width is depending the viewport width
function Slider(){
this.width = viewport.width;
}
Slider.prototype.slide = function(){
console.log(this.width);
}
var slider = new Slider();
slider.slide();
提前谢谢 您可以添加如下回调:
var viewport = {
width: undefined,
onChange: []
}
function initViewport($window){
viewport.width = $window.width();
viewport.onChange.forEach(function(fn) {
fn(viewport.width);
});
}
在滑块中:
function Slider(){
this.width = viewport.width;
viewport.onChange.push(function(newvalue) {
this.width = newvalue;
}.bind(this));
}
您可以添加如下回调:
var viewport = {
width: undefined,
onChange: []
}
function initViewport($window){
viewport.width = $window.width();
viewport.onChange.forEach(function(fn) {
fn(viewport.width);
});
}
在滑块中:
function Slider(){
this.width = viewport.width;
viewport.onChange.push(function(newvalue) {
this.width = newvalue;
}.bind(this));
}
谢谢你的回复。恐怕它返回“未定义”,我不知道为什么。谢谢您的回复。恐怕它返回“未定义”,我不知道为什么。