例如,我有这个JavaScript函数:
function createCroppie() {
var crop = new Croppie(document.getElementById('js-image-editor'), {
enableExif: true,
showZoomer: true,
viewport: { width: y, height: y, type: 'square'},
boundary: { width: x, height: x}
});
}
现在,我需要访问“ crop”变量以在以下代码中使用:
$('.fa-save').on('click', function (ev) {
crop.result ({
type: 'canvas',
size: 'viewport'
}).then(function () {
console.log('upload image complete');
});
});
由于我在此处编写的第二段代码不在同一个函数中,因此如何访问createCroppie函数中的“ crop”变量?
除非使用闭包,否则函数变量将在函数范围内。正如Senal指出的,第一个解决方案是对变量使用全局范围。
要使用闭包进行重写:
function createCroppie() {
var crop = new Croppie(document.getElementById('js-image-editor'), {
enableExif: true,
showZoomer: true,
viewport: { width: y, height: y, type: 'square'},
boundary: { width: x, height: x}
}
return crop;
// or return this;
// this being the elements of the function as an object.
);
}
crop = createCroppie();
查找Croppie文档,它基于创建一个闭包来返回带有变量的对象。无需在其周围包装函数。
var myCroppie = new Croppie(document.getElementById('js-image-editor'), {
enableExif: true,
showZoomer: true,
viewport: { width: y, height: y, type: 'square'},
boundary: { width: x, height: x}
};
但是,您可以使用闭包来扩展库。
function createCroppie() {
var crop = new Croppie(document.getElementById('js-image-editor'), {
enableExif: true,
showZoomer: true,
viewport: { width: y, height: y, type: 'square'},
boundary: { width: x, height: x}
}
function say(message) {
console.log(message);
return this;
}
return this;
);
}
crop = createCroppie();
现在crop是具有对数函数的新的croppie,并且此函数(下面是该函数对象的元素,而不是其后的函数)起作用。
$('.fa-save').on('click', function (ev) {
crop.log('clicked').result ({
type: 'canvas',
size: 'viewport'
}).then(function () {
console.log('upload image complete');
});
});
请注意,闭包函数的say函数需要返回“ this”(Javascript this),以便包括.result函数以允许crop.log.result()存在。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句