[英]access to a variable inside the function in JavaScript
例如,我有这个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”变量?
假设您在点击事件之前初始化了Croppie,则可以执行以下操作
var myCroppie;
function createCroppie() {
myCroppie = new Croppie(document.getElementById('js-image-editor'), {
enableExif: true,
showZoomer: true,
viewport: { width: y, height: y, type: 'square'},
boundary: { width: x, height: x}
});
}
createCroppie();
$('.fa-save').on('click', function (ev) {
myCroppie.result ({
type: 'canvas',
size: 'viewport'
}).then(function () {
console.log('upload image complete');
});
});
除非使用闭包,否则函数变量将在函数范围内。 正如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()存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.