引用方法 Referring to methods
?Constructor?.prototype.?methodName?()
Array.prototype.join()
Array.prototype.join() 指向array的方法join()铺浇,也就是說约啊,JavaScript會把Array實例的方法存儲在對象 Array.prototype 中今布。
JavaScript stores the methods of Array instances in the object Array.prototype.
Layer 3: Constructors—Factories for Instances
Constructors——實例工廠
一個 constructor 函數(shù)有點像是用來生產(chǎn)各種對象的工具吩愧。它只是一個普通的函數(shù)妈候,但是其命名方式、創(chuàng)建和引用都有點不一樣梳猪。
首先称诗,這里共有3個對象, jane 和 tarzan 稱為persons渐白, 它們共享原型對象PersonProto尊浓。
var PersonProto = {
describe: function() {
return 'Person named' + this.name;
}
};
var jane = {
[[Prototype]]: PersonProto,
name: 'Jane'
};
var tarzan = {
[[Prototype]]: PersonProto,
name:'Tarzan'
};
下面我們將這個原型轉(zhuǎn)化成一個構造器-Person,通過構造器來創(chuàng)建實例 jane 和 tarzan:
function Person(name){
this.name=name;}//創(chuàng)建一個構造函數(shù)Person纯衍,注意構造函數(shù)首字母為大寫
Person.prototype.describe = function(){
return 'Person named' + this.name;};//Person.prototype是所有Person示例對象的原型
var jane = new Person('Jane');
jane.describe()
'Person named Jane'//
- Person 被new調(diào)用的時候栋齿,成為一個constructor
- 創(chuàng)建一個存在jane,其prototype=Person.prototype
- 建立了data:通過Person接受一個對象為內(nèi)置參數(shù)this,添加實例的屬性jane
- 函數(shù)Person 有一個屬性prototype,Person.prototype=它的上一級原型圖中為Person.prototype.
- 其原型有一個屬性叫constructor瓦堵,Person.prototype.constructor=Person
Categorizing values :
兩種方法:
typeof value
Returns a string describing the "type" of value.Here are some examples:
typeof true
'boolean'
typeof[ ]
'object'
下表列出了所有的返回結(jié)果
undefined 'undefined'
null 'object'--null 并不是對象基协,這是一個bug。
Function 'function'
All other normal values 'object'
(Engine-created value) js可以創(chuàng)建值菇用,返回種類結(jié)果為任意字符串澜驮。
instanceof:
value instanceof Constr
It returns true if value is an object that has been created by the constructer Constr:
var b= new Bar(); //object created by constructor Bar
b instanceof Bar= true
{ } instanceof Object=true
[ ] instanceof Arrag = true
函數(shù)Boolean(),會把參數(shù)轉(zhuǎn)為布爾值惋鸥,可用來測試一個值是如何被翻譯的:
Boolean(undefined)=false
Boolean(0)=false
Boolean({ }) =true
Boolean([ ]) =true
Binary Logical Operators
如果第一個運算對象滿足條件杂穷,第二個就可以忽略。
比如:
false && foo()
true || foo()
此外卦绣,binary logical operators可以返回任意兩者其中一個操作對象
對于and來說耐量,第一個運算對象如果是false,那么return it. 如果不是滤港,就返回第二個操作對象廊蜒。
比如:
NaN && 'abc'=NaN
123 && 'abc'=''abc
對于or來說,第一個運算對象是truthy溅漾,那么返回第一個山叮,否則就返回第二個。
'abc' || 123='abc'
'' || 123 =123
數(shù)字
javascript中所有的數(shù)字都是浮點數(shù)
1 === 1.0 =true
其中還有一些特殊數(shù)字
- NaN (“not a number”)
用戶錯誤的值:比如
Number('xyz')=NaN
- Infinity
3/ 0=Infinity
字符串
反斜杠backslash () 用于忽略掉后面的字符添履,比如:
'Did she say "Hello"?' "Did she say \"Hello\"?"
單個字符通過方括號來訪問到屁倔,比如
var str = 'abc'; str[1]='b'
屬性length用來計數(shù)一個字符串中字符的長度:比如
'abc'.length=3
字符串的操作符
- 通過+連接,比如
var messageCount = 3;
'You have ' + messageCount + ' messages'
'You have 3 messages'```
- 多步聯(lián)結(jié)字符串暮胧,使用 +=操作符:
var str = '';
str += 'Multiple ';
str += 'pieces ';
str += 'are concatenated.';
str
'Multiple pieces are concatenated.'
### 字符串的方法:
很多方法汰现,以下是其中的一些例子:
'abc'.slice(1)
'bc'
'abc'.slice(1,2)
'b'
'\t xyz '.trim()//去掉whitespace
'xyz'
'abc'.indexOf('b')
1
### 聲明
在javascript中條件和循環(huán)是以下的格式被引入:
1. 條件
一個if的聲明配備一個then的子句,根據(jù)布爾值條件執(zhí)行叔壤。
如果只有一個聲明,可以不用braces口叙,比如:
if (x>0)
return -x;
2. switch 聲明
下面例子中fruit的值來決定執(zhí)行哪個case:
switch(fruit){
case 'banana':
//...
break;
case 'apple':
//...
break;
default:
//...
}
3.循環(huán)for 循環(huán)格式:
> for (init;condition;post-iteration)
statement
**init** 在循環(huán)開始被執(zhí)行炼绘,每次循環(huán)之前**check 條件**,如果條件為FALSE妄田,循環(huán)終止俺亮,每一次循環(huán)迭代之后執(zhí)行**post-iteration**。
for (var i=o;i < arr.length; i++){
console.log(arr[i]);
}
以上示例打印出數(shù)列中所有的元素疟呐。
如果以上以**while循環(huán)**表達則為:
var i=o;
while(i<arr.length){
console.log(arr[i]);
i++;
}
4.do-while循環(huán)
當條件滿足時do-while循環(huán)繼續(xù)執(zhí)行脚曾。條件在body之后,所有body至少被執(zhí)行一次启具。
do {
//....
} while (condition);
在所有循環(huán)中:
- break離開循環(huán)
- continue 開始新的循環(huán)迭代
### 函數(shù)
定義函數(shù)的一種方式是 function declaration(函數(shù)聲明):
function add(param1, param2){
return param1 + param2;
}
call function調(diào)用函數(shù):
add(6,1)
7
add('a','b')
'ab'
另一種定義add()的方式是assigning本讥,即把一個函數(shù)表達式賦值給變量add:
var add=function(param1,param2){
return param1 + param2;
}
所以說,函數(shù)表達式(function expression)產(chǎn)生一個值,可以把它作為參數(shù)賦給其他的函數(shù):
someOtherFunction(function(p1,p2){...});
###函數(shù)聲明被懸置 Function Declarations Are Hoisted
也就是說拷沸,聲明的變量會移動到當前域的開始色查,為此方便你把它引用到后面聲明的函數(shù)中:
function foo() {
bar();//bar is hoisted
function bar (){
...
}
}
var 聲明同樣也可以被懸置,但由它賦的值卻不能被懸置:
function foo() {
bar ();//not ok,bar 沒有定義
var bar = function() {
//...
};
}
### 特殊的變量參數(shù)
在 JavaScript 中你可以使用任意數(shù)量的參數(shù)調(diào)用任意函數(shù)撞芍。
然而秧了,這將使所有的參數(shù)存在,通過特殊的變量`arguments`序无。
函數(shù)中的參數(shù)就像一個數(shù)組验毡,但沒有數(shù)組的方法。
function f() {return arguments}
var args = f('a','b','c');
args.length
3
args[0]//read element at index 0
'a'
### 多余或缺失的參數(shù)
例子:
function f(x,y) {
console.log(x,y);
return toArray(arguments);
}
多余的參數(shù)會被忽略帝嗡,但仍然屬于arguments中晶通。
f('a','b','c')
a b
['a','b','c']
缺失的參數(shù)會獲得一個值=undefined:
f('a')
a undefined
['a']
f()
undefined undefined
[]
###可選的參數(shù)
function pair (x,y){
x=x || 0;
y=y || 0;
return [x,y];
}
**||或** 運算符中,如果第1個運算是真(真意味著不是null,undefined,etc.)丈探,就返回第一個運算符的值录择,否則返回第2個。
pair()//x=空碗降,為假隘竭,返回第二個0;Y同理讼渊,也返回0
[0,0]
pair(3)//x=3动看,為真,返回第一個爪幻,3菱皆;Y為空,返回0
[3,0]
pair(3,5)//x=3挨稿,為真仇轻,返回第一個,3奶甘;Y為5篷店,返回5
[3,5]
### 強制規(guī)定參數(shù)的數(shù)量
function pair(x,y){
if (arguments.length !=2){
throw new Error('need exactly 2 arguments');
}
...
}
### 把 arguments 轉(zhuǎn)化為數(shù)組
function toArray(arrayLikeObject){
return Array.prototype.slice.call(arrayLikeObject);
}
---
### What Is Exception Handling?
對緊密耦合的聲明分組。如果執(zhí)行這些聲明的時候臭家,其中一個導致錯誤疲陕,那么剩下的聲明就無法繼續(xù)。
因此钉赁,我們需要對這些錯誤進行優(yōu)雅地處理蹄殃。
下面看一組代碼(未經(jīng)Exception Handling處理的):
function processFiles(){
var fileNames = collectFileNames();
var entries = extractAllEntries(fileNames);
processEntries(entries);
}
function extractAllEntries(fileNames){
var allEntries = new Entries();
fileNames.forEach(function(fileName){
var entry=extractOneEntry(fileName);
allEntries.add(entry); //(1)
});
}
function extractOneEntry(fileName){
var file= openFile(fileName);//(2)
...
}
...
在(2)代碼行中,最佳的報錯方式是什么你踩?顯然诅岩,聲明(1)不應該再被執(zhí)行讳苦。但我們也不想要終止extractAllEntries()。
那么按厘,我們可以略過當前文件医吊,繼續(xù)執(zhí)行下一個。這里就可以用到exception handling了逮京。
function extractAllEntries(fileNames){
var allEntries=new Entries();
fileNames.forEach(function(fileName){
try {
var entry = extractOneEntry(fileName);
allEntries.add(entry);
} catch (exception){//(2)
errorLog.log(' Error in ' + fileName, exception);
}
});
}
function extractOneEntry(fileName){
var file = openFile (fileName);
...
}
function openFile(fileName){
if (!exists(fileName)){
throw new Error('Could not find file ' + fileName); //(1)
}
...
}
關于 exception handling有兩點:
1. 如果一個問題不能在它發(fā)生的地點被有效地處理卿堂,那么就給一個例外;
2. 找一個處理錯誤的地方:獲得例外懒棉;
###throw //don't do this
throw 語法為:throw ?value?
if(somethingBadHappened){
throw 'Something bad happened';
}
這樣做的好處是草描,JavaScript可以在大部分引擎上自動加上一個堆棧跟蹤stack trace.最簡單的方式是使用內(nèi)置的構造器 Error():
if (somethingBadHappened) {
throw new Error('Something bad happened');
}
function getPerson(id){
if (id <0) {
throw new Error ('ID must not be negative: ' + id);
}
return {id :id};
}
function getPersons(ids) {
var result = [];
ids.forEach(function (id) {
try {
var person = getPerson(id);
result.push(person);
} catch (exception) {
console.log(exception);
}
});
return result;
}
###變量被懸置
function foo() {
console.log(tmp);//undefined
if (false) {
var tmp = 3;//(1)
}
}
執(zhí)行路徑為:
function foo() {
var tmp; //懸置聲明
console.log(tmp);
if (false) {
tmp =3; // assignment stays put
}
}
### 閉包
每一個函數(shù)和其外圍函數(shù)的變量緊密聯(lián)系在一起,即使已經(jīng)離開作用域了策严。
function createIncrementor(start){
return function() { //(1)
start++;
return start;
}
}
var inc = createIncrementor(5);
inc()
6
inc()
7
inc()
8
在(1)中的函數(shù)離開context后仍然和 live 版的 start 保持聯(lián)系穗慕。
閉包,是和外面作用域的變量聯(lián)結(jié)的一個函數(shù)妻导。