![](/img/trans.png)
[英]Is a function declaration (statement) also a function expression technically?
[英]Can a constructor function also be called a function expression?
它們之間的唯一區別是,表達式內部具有某種邏輯,而構造函數僅具有屬性列表嗎? 我很困惑,為什么看起來似乎同一件事有不同的名稱。
//this is an expression
var myFunctionExpression = function(){console.log('hi')};
//this is a constructor
var myConstructorFunction = function(term){this.greeting = term;}
它們之間的唯一區別是,表達式內部具有某種邏輯,而構造函數僅具有屬性列表嗎?
並不是的。
函數表達式 :
var foo = function() { ... }
和功能說明 :
function foo() {
...
}
有兩種定義函數的方法。
構造函數是一種特殊的函數,應使用new
運算符創建對象的新實例。 在此函數內部,您可以使用this
來訪問它創建的實例。 同樣,該函數將其prototype
設置為新創建實例的原型。
構造函數可以用函數表達式聲明
var Foo = function(whatever) {
this.whatever = whatever;
}
var f = new Foo(1);
// f.whatever = 1
或函數語句:
function Foo(whatever) {
this.whatever = 1;
}
var f = new Foo();
// f.whatever = 1
但是請注意,構造函數不必設置任何屬性(這與您的構造函數僅具有屬性列表矛盾)-這將是一個非常有效的構造函數:
function Foo() {}
var f = new Foo();
盡管這個瑣碎的示例沒有多大意義,但引入原型可以顯示出真正的價值:
function Foo() {}
Foo.prototype.bar = function() {}
var f1 = new Foo();
var f2 = new Foo();
// both f1 and f2 have Foo.prototype as their prototype
// both can call .bar() then
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.