这篇文章完全来自Sergio Pereira 的Quick guide to somewhat advanced JavaScript ,没有按照原文翻译,只是自己做了简单的注释。
用JSON的方式创建对象:
var myPet = {
color: ‘black’,
legCount: 4,
communicate: function(repeatCount) {
for( i = 0; i < reapeatCount; i++)
alert('Woorf!');
}
};
alert('my pet is ' + myPet.color);
alert('my pet has ' + myPet.legCount + ' legs');
myPet.communicate(3);
在上面的代码中创建了一个对象的reference,对象包含两个属性(color和legCount)和一个方法(communicate)
在JS中,function也是一个对象,你可以将function作为另外一个function的参数,见下面的代码:
var myDog = {
bark: function() {
alert(”Woorf!”);
}
};
var myCat = {
meow: function() {
alert(”I’m a lazy cat, I will not meow for you.”);
}
};
function annoyThePet(petFunction) {
petFunction();
}
annoyThePet(myDog.bark);
annoyThePet(myCat.meow);
注意,代码的最后两行我们将myDog.bark和myCat.meow传递给annoyThePet方法时没有加”()”,此外我们还可以这样做(我觉得是改变了对象的reference):
myCat.meow = myDog.bark;
myCat.meow(); //alerts “Wroof!”
JS里面对象(Object)和数组(Array)还有着莫名其妙的联系,下面两行用不同方式创建数组,效果一样:
var a = new Array();
var b = [];
对象的属性可以通过取数组元素的方式进行存取:
var obj = {}; // new empty object
obj['member_1'] = 1;
obj['flag_2'] = false;
obj['some_function'] = function(){ /* do something */};
调用的时候同样可以通过存取数组元素的方式:
obj.some_function();
obj['some_function']();
在JS中创建class也是比较诡异的事情,先看看怎么声明class的属性:
//define a class called Pet
var Pet = function(petName, age) {
this.name = petName;
this.age = age;
};
//let’s create an object of the Pet class
var famousDog = new Pet(”Santa\’s Little Helper’, 15);
alert(’This pet is called ” + famousDog.name);
再说说怎么给class定义function(注意代码中的那个”this.name”的使用):
Pet.prototype.communicate = function() {
alert(’I do not know what I should say, but my name is ‘ + this.name);
};
如果你使用prototype.js,创建对象的代码会更清晰:
var Pet = Class.create();
Pet.prototype = {
initialize: function(petName, age) {
this.name = petName;
this.age = age;
},
communicate: function() {
alert(’I do not know what I should say, but my name is ‘ + this.name);
}
};
关于闭包(Closure):
var myArray = ['first', 'second', 'third'];
myArray.each( function(item, index) {
alert(’The item in the position #’ + index + ‘ is: ’ + item);
});
function myIterator(item, index) {
alert(’The item in the position #’ + index + ‘ is: ’ + item);
}
var myArray = ['first', 'second', 'third'];
myArray.each( myIterator);
最后有一个关于this关键字的问题:
var myHelper = {
formFields: [],
emptyAllFields: function() {
for( i = 0; i < this.formFields.length; i++) {
var elementID = this.formField[i];
var field = document.getElementById(elementID);
field.value = ”;
}
}
};
myHelper.formFields.push(’txtName’);
myHelper.formFields.push(’txtEmail’);
myHelper.formFields.push(’txtAddress’);
var clearButton = document.getElementById(’btnClear’);
//clearButton.onclick = myHelper.emptyAllFields;
clearButton.onclick = function() { myHelper.emptyAllFields(); };
上面倒数第二行会导致一个runtime error,原因就在于emptyAllFields方法中的两个this。倒数第二行的代码将clearButton.onclick的reference直接指向了myHelper.emptyAllFields,这样emptyAllFields中的this表示的应该是clearButton,所以自然找不到formFields属性。