素晴らしいですね、疑うのは当然です。これには、JavaScript で関数を渡す方法が関係します。 関数は JavaScript の標準データ型です。 それはオブジェクト全体を渡すことも、コピーすることもできます。 function パラメータリストと関数本体の両方がコピーされ、 が arrayMaker のプロパティ make に割り当てられます。これは、次のように arrayMaker を定義するのと似ています。 var arrayMaker = { someProperty: 'some value here ', make: function (arg1, arg2) { return [ this, arg1, arg2 ] } }; 2 番目の呼び出しがわからない場合イベント処理コードでは、さまざまなバグがよく発生します。例:
function buttonClicked( ){ var text = (this === window) : this.id; alert( text ); var button1 = document.getElementById('btn1 ') ; var button2 = document.getElementById('btn2'); button1.onclick = buttonClicked; buttonClicked(); ;
function buttonClicked(){ var text = (this === window ) ? 'window' : this.id; alert( text ); } var button1 = document.getElementById('btn1'); var button2 = document.getElementById('btn2' );
(1) Constructor I don’t want to delve into the definition of types in Javascript, but at this moment we need to know that there are no classes in Javascript, And any custom type requires an initialization function. It’s also a good idea to define your type using a prototype object (as an attribute of the initialization function). Let’s create a simple type //Declaration A constructor function ArrayMaker(arg1, arg2) { this.someProperty = 'whatever'; this.theArray = [ this, arg1, arg2 ]; } // Statement Instantiation method ArrayMaker.prototype = { someMethod: function () { alert( 'someMethod called'); }, getArray: function () { return this .theArray; } };
var am = new ArrayMaker( 'one', 'two' ); var other = new ArrayMaker( 'first', 'second' ) ;
A very important and noteworthy thing is the new operator that appears before the function call. Without that, your function is just like a global function, and the properties we created All will be created on the global object (window), and you don't want that. Another point, because there is no return value in your constructor, if you forget to use the new operator, some of your variables will be assigned undefined.
So it is a good habit to start the constructor function with a capital letter. This can be used as a reminder not to forget the previous new operator when calling. In this way, the code in the initialization function is as follows Initialization functions you write in other languages are similar. The value of this will be the object you will create