나는 약간의 무식함을 여기에서 느낀다. 그러나 나는 어떤 교육이 나를 해치지 않을 것이라고 생각한다.JQuery 플러그인 범위 문제
문제점을 설명하기 위해 코드를 단순화했습니다. 문제는 init 메소드 내에서 foo()가 호출되면 가정 된 전역, a, b, c 및 설정에 액세스 할 수 없다는 것입니다. 이것들은 메소드 범위 밖에 정의되어 있습니다. 왜 접근 할 수 없습니까? 예를 들어
, 설정이 명확하게 바로 foo를 호출하기 전에 정의, 왜 설정을 볼 수 없습니다 푸 수 있습니까?
(function(jQuery) {
a = new Date();
var b;
var c = 1;
settings = 0; // Here or not - same issue
var methods = {
init : function(settings) {
c = $(this);
settings = jQuery.extend({
id: Math.floor(Math.random()*1001),
x: 3;
etc: 2
}, settings || {});
m = 1;
foo();
}
};
function foo()
{
x = settings.x; // settings is not defined
var n = c.m;
return x;
}
jQuery.fn.bar= function(method) {
if (methods[method]) // If we have a method that exists
{
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
else if (typeof method === 'object' || ! method) // Otherwise if we get passed an object (settings) or nothing, run the init.
{
return methods.init.apply(this, arguments);
}
else
{
$.error('Method ' + method + ' does not exist'); // Otherwise we have an error.
}
};
})(jQuery);
아이디어가 있으십니까?
// Here there is a global settings
init : function(settings) {
// Here there is a local settings
// Changes made to it won't affect the global
푸라고 그래서 설정이 여전히 0이며, 당신이 정의되지 Number(0).x
에 액세스 : 당신이 당신의 init 함수에 인수로 정의 할 때이 설정의 로컬 복사본을 만드는
그렇지 않은 중요하지만, 당신이 당신의 예에서 페이지 – jammypeach
의 상단에있는 설정을 선언 위치를 var에 = 할당이없는이 "설정이"정의되지 않은, 또는 "settings.x"입니다 정의되지? foo() 설정에서 0은 같아야하지만 settings.x는 정의되지 않아야합니다 ... 확인할 수 있습니까? – Timbo
@Timbo - 확인 ... settings = 0, settings.x는 정의되지 않았습니다. 범위는 무엇입니까? –