Javascript カツレツからハエを分離

誰かのために頻繁にPravyaは(それだけでなく)javascriptコードに出くわします

プログラマーVasyaが「ハエをカツレツから分離しない」状況。 グローバル変数の干渉を意味します

これらの変数と関数が何らかの形で互いに関連していても、関数と一緒に。



次に、Vasyaがコードを残して去ると、Petyaが来て、Vasyaのコードで作業することを余儀なくされる場合が発生します。



プチの状況は最も快適ではありません。 どういうわけか彼の神経と時間を節約するために、私が提供したいjavascriptテンプレートが必要です。



var someComponent = ( function () {

var self = this ;



// Methods

this .method1 = function () {

}

this .method2 = function () {

}

this .method3 = function () {

}



// Constructor

this .prop1 = 'foo' ;

this .prop2 = 'bar' ;

this .prop3 = 'qaz' ;



return this ;



})();



* This source code was highlighted with Source Code Highlighter .






それは超自然的なことではないように思えますが、何らかの理由で多くのプログラマーが望んでいないか、

データとメソッドを組み合わせるのを忘れてください。



そして、1つのグローバル変数someComponentの代わりに、名前空間を詰まらせる束があり、

コードの保守が難しくなります。



さらに、このアプローチのもう1つの利点は、コールバック関数からオブジェクトのコンテキストに簡単にアクセスできることです。

作業コードの例:



var periodInfo = ( function (sportKind) {

var self = this ;



this .sportKind = sportKind || 'football' ;



this .hintBox = null ;

this .hintBoxTop = null ;

this .hintBoxLeft = null ;



this .inputElement = null ;

this .currentPeriod = 1;

/**

* Show panel.

*/

this .show = function () {

$( '#goals-panel' ).show();

}

/**

* Hide panel.

*/

this .hide = function () {

$( '#goals-panel' ).hide();

}

/**

*

*/

this .clear = function () {

$( '[class~="home"]' ).remove();

$( '[class~="away"]' ).remove();

}



$( document ).ready( function () {

// .

self.hintBox = $( '#hint-box' );

$( document ).click( function () {

self.hide_hint_box();

});

});



return this ;

})();




* This source code was highlighted with Source Code Highlighter .








これは、あなた自身や他の人々の生活を簡単かつ効果的に簡単にする方法です。



// 更新

コメントで述べたすべてのことで、次のようになります。

function Person(firstname, lastname, age) {

var self = this ;

// Assign values to private members.

var firstname = firstname;

var lastname = lastname;

var age = age || 'unknown' ;



// Private method.

this .name_fix_up = function (name) {

return name[0].toUpperCase() + name.substr(1);

}



// Public methods.

return {

get_age: function () {

return age;

},

get_name: function () {

return self.name_fix_up(firstname) + ' ' + self.name_fix_up(lastname);

}

}

}



var p = new Person( 'vasya' , 'pupkin' , 23);

alert( "It's " + p.get_name() + ', he is ' + p.get_age() + ' years old.' )

// Trying to access private method.

p.name_fix_up( 'sergey' );



* This source code was highlighted with Source Code Highlighter .








プライベート/パブリックメソッドおよびプロパティをサポートするテンプレート。



All Articles