它们之间的唯一区别是表达式内部有某种逻辑,而构造函数只有一个属性列表吗?我很困惑为什么看似相同的东西有不同的名称..
//this is an expression
var myFunctionExpression = function(){console.log('hi')};
//this is a constructor
var myConstructorFunction = function(term){this.greeting = term;}
最佳答案
Is the only difference between them that an expression has some kind of logic inside it, while a constructor function only has a list of properties?
不是真的。
函数表达式:
var foo = function() { ... }
和函数语句:
function foo() {
...
}
定义函数的两种不同方式。
构造函数 是一种特殊的函数,应该使用new
运算符创建对象的新实例。在此函数中,您可以使用 this
访问它创建的实例。此外,该函数将其 prototype
设置为新创建实例的原型(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();
虽然这个微不足道的例子没有多大意义,但引入原型(prototype)显示了真正的值(value):
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
关于javascript - 构造函数也可以称为函数表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54280350/