[譯] Javascript初學者需要知道的十件事


原文:http://www.quora.com/JavaScript/What-are-the-top-ten-things-a-beginner-must-know-about-JavaScript


 

 

1. Javascript沒有類的概念。一般使用原型鏈繼承(prototypal inheritance)來模擬類。

 

2. 除了null和undefined之外的任何數據類型都能表現成Object (behave like an object),包括Number類型和Function類型。

var n = 42;
function f() { alert("foo"); };

alert("n is " + n.toString()); // "n is 42"
alert(f.name + " is a function"); // "f is a function"

注意,是“表現為object”,而不是“是object”。事實上,number, string和boolean是基本類型(primitives),除了這三個之外的都可以算作object,比如一個正則表達式也是一個object。 當需要訪問基本類型變量的屬性時,那些基本類型變量將被臨時轉換成object。 例如:

"foobar".big();
// is equivalent to
new String("foobar").big();

3.14.toFixed();
// is equivalent to
new Number(3.14).toFixed()

另外,不能強行給基本類型變量(number, string, boolean)加上私有屬性。

var a = "mystring",
    b = new String( "mystring" );

Object.defineProperty( b, 'foo', { value: 42, enumerable: false });
console.log(b.foo); // 42
Object.defineProperty( a, 'foo', { value: 42, enumerable: false });
// TypeError: Object.defineProperty called on non-object

// trying another way:
a.foo = 42;
// remember, this is equivalent to:
// new Number(a).foo = 42;
// …so the 'foo' property is defined on the wrapper, not on 'a'
console.log(a.foo); // undefined

 

3. 如果變量名前不加上var,那么這個變量就是全局的。

function setGlobal() {
  a = 42;
}

function setLocal() {
  var b = 23;
}

setGlobal();
alert(a); // 42

setLocal();
alert(b); // ReferenceError: b is not defined

 

4. this指針是由調用函數賦予的, 而不是由被調函數自身定義的。 例如:

var a = {}, b = {};

a.foo = 42;
b.foo = 18;
a.alertFoo = function() { alert(this.foo); };

a.alertFoo(); // 42
a.alertFoo.call(b); // 18

 

5. 嚴格的相等判斷應該使用===。例如 :

0 == false 為真, 但是 0 === false 為假。

 

6. 0, undefined, null, "", NaN 都是假值 (falsy)。

 這些值全都等同於false,但他們之間不能相互替換。

 

7. 變量聲明會被提升到當前作用域的頂端。 例如:下述代碼中,你認為調用foo函數會返回什么?

var a = 2;

function foo() {
    return a;
    var a = 5;
}

它將返回undefined。 上述代碼等同於下述代碼:

var a = 2;

function foo() {
    var a; // 'a' declaration is moved to top
    return a;
    a = 5;
}

另一個例子: 下述代碼中,調用函數foo后變量a的值是什么?

var a = 42;

function foo() {
    a = 12;
    return a;
    function a(){}
}

答案是42。因為foo函數中變相聲明了a變量,因此a成了局部變量了。

function foo() {
    function a() {} // local 'a' is a function
    a = 12; // local 'a' is now a number (12)
    return a; // return the local 'a' (12)
}

 

8. 參數在函數聲明中可以省略, 例如:

function hello(name, age) {
  alert("Hello "+name+", you’re "+age+" years old!");
}

hello("Anon", 42); // "hello Anon, you’re 42 years old!"
hello("Baptiste"); // "hello Baptiste, you’re undefined years old!"
hello("Bulat", 24, 42); // "hello Bulat, you’re 24 years old!"

 

9. 對於字符串,使用雙引號""和單引號''的效果是一樣的。

 

10. Javascript代碼可以在瀏覽器環境之外運行, 比如在Terminal或者HTTP服務器上。(例如 Node.js)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM