简体   繁体   English

在Javascript中,函数声明是创建构造函数的唯一方法吗?

[英]In Javascript, is function declaration the only way to create a constructor?

In JavaScript, is function declaration the only way to create a constructor that can be used to instantiate a new object. 在JavaScript中,函数声明是创建可用于实例化新对象的构造函数的唯一方法。 If so, Why ? 如果是这样,为什么? This question arises from the following code. 这个问题来自以下代码。

var customevent = {
        prop1 : "div",
        prop2 : "div2"
    }

    var myevent_obj = new customevent();

Browser JS console show 浏览器JS控制台显示

SyntaxError: customevent is not a constructor.

By definition, a constructor is an object that implements the internal [[call]] and [[Construct]] methods. 根据定义, 构造函数是实现内部[[call]][[Construct]]方法的对象。 Except for a few built–in functions, all native functions are constructors. 除了一些内置函数之外,所有本机函数都是构造函数。 Most host functions are not constructors, though some are. 大多数宿主函数不是构造函数,尽管有些是。

EMCAScript 2015 also defines exotic function objects, which might be built–in but need not be constructors. EMCAScript 2015还定义了外来函数对象,这些对象可能是内置的,但不一定是构造函数。

There are two methods for creating a native function that can be a constructor: 有两种方法可以创建构造函数的本机函数:

  1. Function declaration: function MyConstructor(){...} 函数声明: function MyConstructor(){...}
  2. Function expression (usually through assignment): var MyConstructor = function(){...}; 函数表达式(通常通过赋值): var MyConstructor = function(){...};

That's it. 而已。

In the OP: 在OP中:

var customevent = {
        prop1 : "div",
        prop2 : "div2"
    }

customevent is an Object, not a Function. customevent是一个对象,而不是一个函数。 Plain objects don't implement either [[Call]] or [[Construct]] internal methods, therefore they can't be constructors. 普通对象既不实现[[Call]]也不实现[[Construct]]内部方法,因此它们不能成为构造函数。 They can be used as prototypes though: 它们可以用作原型:

function customConstructor(){}
customConstructor.prototoype = customevent;

or 要么

var newCustomEvent = Object.create(customevent);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM