JavaScript 的變數都有物件的型態跟特性,什麼型態都可以當成物件來用。物件是指?可以擁有資料跟方法的變數。
例如這個 obj 物件。
var obj = {};
obj.data = 1;
obj.method = function() { console.log("data = " + this.data); }
obj.method();
//print 1
而其他也是物件的型態有
陣列
var arr = [1, 2, 3];
arr.data = 1;
arr.method = function() { console.log("data = " + this.data); }
arr.method();
//data = 1
console.log(arr);
//[1, 2, 3]
console.log(arr[0]);
//1
console.log((null, arr));
//[1, 2, 3, data: 1, method: function]
1
函式
var fn = function() { return "hello"; };
fn.data = 1;
fn.method = function() { console.log("data = " + this.data); }
fn.method();
//data = 1
console.log(fn);
//function () { console.log("hello"); }
console.log(fn());
//hello
陣列跟函式都有他原本的功能,但是也帶有物件的特性。就連原生型態數字、布林、字串也都有物件的版本,可以用物件的方式處理。
var n = new Number(100);
n.data = 1;
n.method = function() { console.log("data = " + this.data); }
n.method();
//data = 1
console.log(n);
//Number {data: 1, method: function}
console.log(n+1);
//101
如果沒看到建構 n 的方法,會不會把 n 認作一個物件勒~所以有一些函式可以用來判別變數的型態
n instanceof Number //true typeof n // object type of 1 // number n.valueOf(); //100 n.toString(); //"100"
所以複寫 valueOf 跟 toString 可以讓一般物件運作起來像是數字或字串,js 會在執行運算時轉型來決定呼叫哪個函式。
var what = {valueOf: function() { return 100;}};
console.log(what+50);
//150
what = {toString: function() { return "I am what"; }}
console.log("Who are you. "+ what);
//Who are you. I am whatwha
