標籤:
function: function本身是一個object,它可以被賦值給任何變數
immediate invoked function expression(IIFE): function(){}()
method vs function: 一個method是一個對象的一個函數屬性(a method is a function that is a property of an object)例如:
var console={
log:function(){}
}
console.log(“log是console的method!");
String methods:
下面的方法或者屬性是string對象定義的方法或者屬性!
length: 這個length實際上是一個屬性,而不是一個方法。
indexOf
var line = "HAL: I‘m sorry, Dave. I‘m afraid I can‘t do ?that";alert( line.indexOf("I‘m") ); // 5alert( line.indexOf("I‘m", 6) ); // 22
slice,substr,substring函數:
var greeting = "Hello, Andrew, what‘s up?",name = greeting.slice(7, 13);alert(name); // Andrew
split:該函數將一個字串使用空格符作為分割依據將每個單詞分開放到一個數組中
var arr = "apples oranges peaches bananas".split(" ");console.log(arr); // ["apples", "oranges", "peaches", ?"bananas"]
toLowerCase, toUpperCase
Date Methods
Date object有很多實用的方法可供使用
getDate,getDay,getFullYear,getHours,getMilliseconds,getMinutes,getMonth,getSeconds,getTime,getTimezoneOffset
setDate,setFullYear,setMinute,setMonth,setSeconds,setTime,setMilliseconds,setHours,
parse:可以用於講一個字串解析為Date object
alert( Date.parse("June 18, 1970") ); // 14529600000alert( Date.parse("2010/11/11") ); // 1289451600000var d = new Date(Date.parse("1995/04/25")); // Tue Apr 25 ?1995 00:00:00 GMT-0400 (EST)alert(d);Array methods
join:這是和split相反的動作,它將把數組中的所有元素結合在一起形成一個string
alert( ["cats", "dogs", "hamsters", "fish"].join(‘ ‘) );// "cats dogs hamsters fish"alert( "this should not have spaces".split(" ").join("_") );// "this_should_not_have_spaces"
pop/shift:
var arr = ["cats", "dogs", "hamsters", "fish"];console.log( arr.pop() ); // "fish"console.log( arr.shift() ); // "cats"console.log( arr ); // ["dogs", "hamsters"]
push/unshift:push將在數組的尾部增加一個item,unshift則在數組的開始增加一個item
var arr = ["Beta", "Gamma"];arr.push("Delta");console.log(arr); // ["Beta", "Gamma", "Delta"];arr.unshift("Alpha");console.log(arr); // ["Alpha", "Beta", "Gamma", "Delta"]
reverse:
alert( ["Crockford", "Resig", "Zakas"].reverse() ); ?// "Zakas, Resig, Crockford"
slice:有時,你希望將你的數組slice成多個部分,這個slice就提供這個功能。包含兩個參數:index of the starting element and index of the element after the last one you want to slice.
alert( ["a", "b", "c", "d", "e"].slice(2, 4) ); ?// ["c", "d"]alert( ["f", "g", "h", "i", "j"].slice(1) ); ?// ["g", "h", "i", "j"]
sort:按照字母排序:
["d", "e", "c", "a", "b"].sort(); // ["a", "b", "c", "d", ?"e"][0, 5, 10, 15, 20, 25].sort();//[0, 10, 15, 20, 25, 5].
在上面對數位排序可能並不是你希望得到的效果,一個可行的方案是sort函數傳入一個函數:
var arr = [5, 2, 3, 4, 1,10,20];arr.sort(function (a, b) {return a - b;});console.log(arr); // [1, 2, 3, 4, 5 ,10 ,20];Math functions
javascript也提供了一個Math 對象,你雖然不能像Date對象一樣二次建立對象,但是你卻可以直接調用Math對象的方法
min,max,random,round,ceil,floor,pow,
alert( Math.min(9, 1, 4, 2) ); // 1alert( Math.random() ); // 0.5938208589795977 (you‘ll ?probably get something else)alert( Math.random() * 10 ); // 6.4271276677027345 (again,?your mileage may vary)alert( Math.round(10.4) ); // 10alert( Math.round(10.5) ); // 11alert( Math.ceil(10.4) ); // 11alert( Math.floor(10.5) ); // 10function getRandomNumberInRange(min, max) {return Math.floor( Math.random() * (max - min + 1) + ?min);}alert( getRandomNumberInRange(0, 100) ); // 39; you‘ll ?probably get something different.This
This是javascript預留的keyword,你可以將this想象成一個你不能控制的動態變數。this變數的值將隨著你在代碼的哪一個地方而不斷變化其值:
預設情況下,this將指向window這個global對象。this沒有一個合適的名字,但是他卻有一個屬性指向它自己:window.如果你看看下面這個小的代碼,就有些感覺了:
var my_variable = "value";function my_function () { return "another_value" }alert( this.my_variable ); // "value"alert( this.my_function() ); // "another_value"var global = {window : global. . .};this = global;
這意味著你可以訪問你的全域變數或者函數作為window的屬性,而這比用this來訪問這些全域變數函數更加普遍。這依然有點搞,因為你可以訪問window對象來使用global對象上的函數或屬性,即使this可以指向其他的對象。甚至,你不用使用window.xx的方式調用,除非你有一個local的變數或者函數而覆蓋了全域的函數或變數!
new keyword
第一種改變this指標的方法是使用new 關鍵字:
你可能知道了javascript對象是什麼(屬性和函數的封裝)。將相關的功能封裝到一個合適的object中並且通過合適的介面來訪問是一個非常非常非常基礎的OOP編程模式。Classes就像一個藍圖:他們不是實際的對象,但是他們描述了一旦通過該class建立一個object,那麼這個object應該具備的函數和變數。javascript是物件導向的,但是它卻不用class這個概念。想法,它使用prototypes這個概念。prototypes是一些實際的對象objects,我們可以使用這些對象objects作為鮮活的建立其他對象的藍圖”對象“。
在其他語言中,比如c++,使用一個建構函式來建立新的對象。而在javascript中,建構函式是普通的函數,如果在它前面添加一個new關鍵字則可以建立新的對象。
比如我們要建立truck對象,
function Truck(model) {this.num_of_tires = 4;this.kilometers = 0;this.model = model;}var my_truck = new Truck("Hercules");console.log(my_truck);
上面的代碼注意兩點:首先,我們定義所有的變數作為this對象的屬性;其次,我們沒有從這個函數中返回任何東西。這兩點是因為我們計劃使用new關鍵字來調用這個函數建立對象。注意我們是如何使用new關鍵字的。它做了兩件事:首先,它更改this指標指向一個新的乾淨的對象。很明顯,我們然後可以增加我們定製的屬性在這個函數中。第二件new乾的事情是:它將this返回。現在my_truck變數將指向新的對象,這個my_truck就像我們下面的代碼一樣的結果:
var my_truck = {num_of_tires : 4,kilometers : 0,model : "Hercules"};console.log(my_truck);
這就是使用new的想法:我們獲得一個建立新對象的超級簡單的方法。很明顯,你如果僅僅需要一個或兩個簡單的對象,你不需要這麼做。通常你在需要有很多功能並且希望打包到一個對象中時,你才需要這種new的模式,或者你希望建立一系列類似的對象時,也可以使用new方法來建立對象。
call and apply
第二種更改this指標的方法是call或者apply.在javascript中一切皆為對象---即便function也是對象。既然function是對象,那麼他們也可以有屬性和方法(property,method)。call和apply就是每一個function對象的兩個預設方法。
這兩個方法存在的價值就是在函數中修改this指標:
function Truck (model, num_of_tires) {this.num_of_tires = num_of_tires;this.kilometers = 0;this.model = model;}var basic_vehicle = { year : 2011 };Truck.call(basic_vehicle, "Speedio", 4);console.log(basic_vehicle);
小知識點:primitive vs reference values:你可能想,雖然我們更改一個已知的對象,我們會丟失那些變更,除非我們將他們賦值給一個新的變數。如果變數是一個primitive value,那麼這將是對的。然而,objects(arrays)是referrnce values:values passed by referrnce.一個primitive value(比如一個string或者number)是在電腦記憶體中儲存的,而我們使用一個變數來訪問它。當我們將這個變數傳給一個函數時,我們會copy那個值到一個新的記憶體,而將函數參數指向這個新的copy記憶體,而在函數中對這個copy操作,因此原始的primitive value並不會被變更。(因為記憶體不同),但是當我們使用reference value時則不同:當我們傳遞一個object或者一個array給一個function時,形式參數將指向原始object/array相同的記憶體。這意味著,Truck.call(basic_vehicle)中的this和函數外的basic_object中的this是完全一個basic_object.所以沒有必要做任何assign動作,因為basic_vehicle現在已經有了由Truck賦值的所有屬性。如果我們將Truck.call(basic_vehicle)的傳回值付給一個變數,將會發生什麼,它將會是undefined,因為Truck without new將不會返回任何東西!
在這裡,我們通過Truck函數的call方法來調用Truck函數。call的第一個參數是我們希望在函數中this所指向的對象。既然我們沒有使用new來調用Truck,它將不會建立任何新的對象或者返回this.這也是我們所希望的,因為我們僅僅是在修改已經存在的對象,而不是重新建立一個!
在將成為this所指向的對象參數後(你可以稱為函數的上下文context),我們可以傳入任何需要的參數。這些將作為參數被傳入將被執行的函數。上面的例子中,第二個參數"Speedio"將被傳給Truck函數作為其第一個Parameter。第三個參數6將成為Truck的第二個參數。
和call向對應,還有一種方法叫做apply.兩者的區別是:apply只接受兩個參數。第一個是context object,第二個是將被傳入function的一個參數的數組。如果你有一個作為數組的參數,這種方法將非常有用。例如,
function Truck (model, num_of_tires) {this.num_of_tires = num_of_tires;this.kilometers = 0;this.model = model;}var basic_vehicle = { year : 2011 },user_input = "Speedio 18";Truck.apply(basic_vehicle, user_input.split(" "));console.log(basic_vehicle);Inside an Object
還有另外一種方法可以更改this的值。
var waitress = {name : "Ashley",greet: function (customer) {customer = customer || " there!";return "Hi " + customer + " My name is " + ?this.name + "; what can I get you?";}};alert( waitress.greet("Joe") ); // Hi Joe My name is ?Ashley; what can I get you?
javascript fundamental concept