7/31/2013
4:52:00 PM 0

Javascript Constructor Property

Javascript constructor 是建構該物件之執行個體的函式參考,所以當建立該物件時就會賦予 constructor 屬性值
function Employee(name, department)
{
    this.name = name;
    this.department = department;
}

var e1 = new Employee('Albert', 'accounting');
var e2 = new Employee('Grace', 'sales');
console.log(e1 instanceof Employee);
console.log(e2 instanceof Employee);
console.log(e1.constructor == Employee);
console.log(e2.constructor == Employee);
output
--------------------------------------------
true
true
true
true

但如果使用 constructor 屬性來判斷 constructor function 是不安全的, 因為 constructor 是可以被修改的
function NewType(){};

e1.constructor = NewType;
console.log(e1 instanceof Employee);
console.log(e1 instanceof NewType);
console.log(e1.constructor == Employee);
console.log(e1.constructor == NewType);
console.log(e1.constructor instanceof Function);
output
--------------------------------------------
true
false
false
true
true
var newTypeInstance = new NewType();
e2.constructor = newTypeInstance;
console.log(e2 instanceof Employee);
console.log(e2 instanceof NewType);
console.log(e2.constructor == Employee);
console.log(e2.constructor == NewType);
console.log(e2.constructor instanceof Function);
console.log(e2.constructor == newTypeInstance);
output
--------------------------------------------
true
false
false
false
false
true

Javascript 除了基本型別(primitive types)之外,其餘都是物件,因此都有constructor屬性
console.log(this.constructor);
console.log(RegExp.constructor);
console.log(Date.constructor);
console.log("xyz".constructor);
output
--------------------------------------------
function Window() { [native code] }
function Function() { [native code] }
function Function() { [native code] }
function String() { [native code] }

Wrapper Object 上場
var num = 1;
console.log(num.constructor);
output
--------------------------------------------
function Number() { [native code] }

一般建構函式不需要有 return, 當有設定回傳值時, 會改變 constructor 所參考的值
1. 回傳值是物件 : 會改變 constructor 所參考的值,並且影響 instanceof 判斷結果
2. 回傳值是基本型別 : 不影響 constructor 所參考的值

function Book1(isbn, name)
{
    this.isbn = isbn;
    this.name = name;
 
    return [isbn, name];
}
var b1 = new Book1('123', 'Book1');
console.log(b1 instanceof Book1);
console.log(b1 instanceof Array);
console.log(b1.constructor == Book1);
console.log(b1.constructor == Array);
console.log("###############################");
function Book2(isbn, name)
{
    this.isbn = isbn;
    this.name = name;
 
    return true;
}
var b2 = new Book2('456', 'Book2');
console.log(b2 instanceof Book2);
console.log(b2 instanceof Array);
console.log(b2.constructor == Book2);
console.log(b2.constructor == Array);
output
--------------------------------------------
false
true
false
true
###############################
true
false
true
false

0 comments:

Post a Comment