對象
區別(特點):與C++,Java,C#不同,JavaScript生成的對象可以對其進行動態的添加,修改,刪除對應的屬性,比較靈活
構造函數
- 原理(與函數方法的不同)
- 在函數體(構造函數)最前面隱式添加 this
function Animal(){
var this = {
__proto__ : Animal.prototype
};//隱式添加
}
- 執行賦值語句 this.key =value;
- key:對象的屬性(要添加的,要賦值的)關鍵詞
- value:對應的值或內容
- 隱式返回this 即 return this;
構造函數與函數的關系與區分
- 開發時,聲明構造函數使用大駝峰原則命名,聲明函數時使用小駝峰命名原則
- 使用函數來模擬構造函數
function TestObject(name,age){
var that= {};
that.name = name;
that.age = age;
return that;
}
var test = TestObject('15','52');//注意此時沒有使用關鍵詞new,使用new時會返回原始值,若指定返回其他內容則會強制修改為this
New解釋
var testNum = new Number();//此時會生成對象,并不是Number,但是參與運算后可以轉化為Number
testNum.a = "abc";//此時可以添加屬性值,與對象相似
包裝類
var testNum = 4;
testNum.a = "abc";//此時可以添加屬性值,但是不會報錯,輸出為undefined
//隱式環節:包裝類
//1. testNum = new Number(4);
//2. testNum.a ="abc";
//3. delete testNum ;
var str= "abcd";
str.length = 2;
console.log(str);//輸出為abcd
console.log(str.length);//輸出為4
//隱式環節:包裝類
//1. new String("abcd").length = 2
//2. delete new String("abcd")
- 練習
var str= "abc";
str += 1;
if(str.length == 6){
str.sign = "Hello World";
}
console.log(str.sign);//結果為undefined