標籤:blog http io ar 使用 for sp div on
--------------------------------------------------------------------------------------------
變數:自由的 => 屬性:屬於一個對象
函數:自由的 => 方法:屬於一個對象
函數:
function a()
{
console.log(‘a‘);
}
方法:
var arr = [1, 2, 3, 4];
arr.a = function()
{
console.log(‘a‘);
}
===================================================
簡單的例子:
var arr = new Array(1, 2, 3);
這裡的Array就是類,arr就是對象。
理解this:
arr = [1, 2, 3, 4];
arr.a = 5;
arr.showA = function()
{
console.log(this.a); //this為arr
}
oDiv.onclick = function()
{
console.log(this); //this為oDiv
}
this:當前發生事件的對象,當前方法屬於誰就代表誰。
===================================================
混合方式構造對象:
原則 => 建構函式:加屬性
原型:加方法
對象命名規範 => 類名首字母大寫
function CreatePerson(name, sex) //建構函式
{
//成員屬性
this.name = name,
this.sex = sex,
}
CreatePerson.prototype.showName = function() //在原型裡加方法
{
console.log(‘My Name Is ‘ + this.name);
}
CreatePerson.prototype.showSex = function()
{
console.log(‘My Sex Is ‘ + this.sex);
}
var obj = new CreatePerson(‘Cw‘, ‘male‘);
var obj2 = new CreatePerson(‘Girl‘, ‘female‘);
console.log(obj.showName == obj2.showName); //true;
//同一方法,不同對象,如果不使用原型添加則不相等
//原型屬於類,在對象中加入自己的屬性、方法,原型修改將對已有對象產生影響。
//給對象添加方法,影響當前; 給原型添加方法,影響一類。原型的缺陷:無法限制覆蓋。
===================================================
為對象添加方法和屬性(注意):
事件處理中this的本質 => window
方法屬於誰
不能在系統對象中隨意附加方法、屬性,否則會覆蓋已有方法、屬性。
object對象(空的)
其它對象:Date,Array,RegExp
function createPerson(name, sex) //建構函式
{
var obj = new Object(); //建立對象
obj.name = ‘Cw‘; //添加
obj.sex = ‘male‘;
obj.showName = function()
{
console.log(‘My Name Is ‘ + this.name);
}
obj.showSex = function()
{
console.log(‘My Sex Is ‘ + this.sex);
}
obj.showName();
obj.showSex();
return obj; //返回對象
}
var obj = createPerson(‘Cw‘, ‘male‘);
obj.showName();
obj.showSex();
缺點:如果要建立多個對象,多次調用方法,對象方法重複建立。
===================================================
工廠方式:調用函數前加new,系統自動建立一個Null 物件並返回
function createPerson(name, sex)
{
this.name = ‘Cw‘;
this.sex = ‘male‘;
this.showName = function()
{
console.log(‘My Name Is ‘ + this.name);
}
}
var obj = new createPerson(‘Cw‘, ‘male‘);
原型的使用:
var arr = new Array(12, 13);
var arr2 = new Array(14, 15);
Array.prototype.sum = function()
{
var result = 0;
for(var i = 0; i < this.length; i++)
{
result += this[i];
}
return result;
}
console.log(arr.sum());
console.log(arr2.sum());
Link: http://www.cnblogs.com/farwish/p/4055675.html
------------------------------------www.chenwei.ws------------------------------------
[JS]如何理解JS中的類和對象