js Function 加不加new 详解

以下来自:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

new constructor[([arguments])]

Parameters

constructor
A function that specifies the type of the object instance.
arguments
A list of values that the constructor will be called with.

Description

Creating a user-defined object requires two steps:

  1. Define the object type by writing a function.
  2. Create an instance of the object with new.

To define an object type, create a function for the object type that specifies its name and properties. An object can have a property that is itself another object. See the examples below.

When the code new foo(...) is executed, the following things happen:

  1. A new object is created, inheriting from foo.prototype.
  2. The constructor function foo is called with the specified arguments and this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments.
  3. The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

You can always add a property to a previously defined object. For example, the statement car1.color = "black" adds a property color to car1, and assigns it a value of "black". However, this does not affect any other objects. To add the new property to all objects of the same type, you must add the property to the definition of the Carobject type.

You can add a shared property to a previously defined object type by using the Function.prototype property. This defines a property that is shared by all objects created with that function, rather than by just one instance of the object type. The following code adds a color property with value null to all objects of type car, and then overwrites that value with the string "black" only in the instance object car1. For more information, see prototype.

 function Car() {}
 car1 = new Car()
 
 alert(car1.color)           // undefined
 
 Car.prototype.color = null
 alert(car1.color)           // null
 
 car1.color = "black"
 alert(car1.color)           // black

Example: Object type and object instance

Suppose you want to create an object type for cars. You want this type of object to be called car, and you want it to have properties for make, model, and year. To do this, you would write the following function:

function car(make, model, year) {
   this.make = make;
   this.model = model;
   this.year = year;
}
Now you can create an object called mycar as follows:

var mycar = new car("Eagle", "Talon TSi", 1993);
This statement creates mycar and assigns it the specified values for its properties. Then the value of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on.

You can create any number of car objects by calls to new. For example:
var kenscar = new car("Nissan", "300ZX", 1992);

Example: Object property that is itself another object

Suppose you define an object called person as follows:

function person(name, age, sex) {
   this.name = name;
   this.age = age;
   this.sex = sex;
}

And then instantiate two new person objects as follows:

var rand = new person("Rand McNally", 33, "M");
var ken = new person("Ken Jones", 39, "M");

Then you can rewrite the definition of car to include an owner property that takes a person object, as follows:

function car(make, model, year, owner) {
   this.make = make;
   this.model = model;
   this.year = year;
   this.owner = owner;
}

To instantiate the new objects, you then use the following:

var car1 = new car("Eagle", "Talon TSi", 1993, rand);
var car2 = new car("Nissan", "300ZX", 1992, ken);

Instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the parameters for the owners. To find out the name of the owner of car2, you can access the following property:

car2.owner

详解new function(){}和function(){}() 区别分析

只要 new 表达式之后的 constructor 返回(return)一个引用对象(数组,对象,函数等),都将覆盖new创建的匿名对象,如果返回(return)一个原始类型(无 return 时其实为 return 原始类型 undefined),那么就返回 new 创建的匿名对象

情景一:
var yx01 = new function() {return "圆心"}; 
alert(yx01); 
我们运行情景一代码,将返回显示“[object object] ”,此时该代码等价于: 

function 匿名类(){ 
    return "圆心"; 

var yx01 = new 匿名类(); 
alert(yx01);我们对情景一的代码进行下面改造: 

var yx01 = new function() {return new String("圆心")}; 
alert(yx01); 
我们运行,将会发现返回的是“圆心”,这是为什么呢? 

只要 new 表达式之后的 constructor 返回(return)一个引用对象(数组,对象,函数等),都将覆盖new创建的匿名对象,如果返回(return)一个原始类型(无 return 时其实为 return 原始类型 undefined),那么就返回 new 创建的匿名对象
由于 new String 会构造一个对象,而不是一个 string 直接量,且new String(x) 如果带参数,那么alert它的时候就会返回 x。所以 yx01 将返回 new String(”圆心”) 这个对象,而 alert yx01 则显示 “圆心”。 

情景二: 

var yx02 = function() {return "圆心"}(); 
alert(yx02);我们运行情景二代码,将返回显示“圆心”,此时该代码等价于: 

var 匿名函数 = function() {return "圆心"}; 
yx02 = 匿名函数(); 
alert(yx02);很明显,yx02 返回的是匿名函数的执行结果值,即 yx02 为:“圆心”。 

当然匿名函数的执行结果也可以为一个匿名对象。具体常见应用可以看《Javascript的一种模块模式

具体有

var func=function(a,b)
{
this.a=a;
this.b=b;
}
var funcO=new func(1,2);
Function.prototype.say=function(){ alert('jack');};

document.write(func.say()); //可以
document.write(funcO.say());//报错

在上面例子中。func是object type对象,funcO是对象实例object instance。

凡是Function类型的对象都可以调用Object的prototype,但返过来就不行。

上面的最后一句报错funcO.say() funcO没有say方法。就说明了这个问题。

obejct type的constructor都返回Function类型。但是object instance返回的是object type。

document.write(func.constructor==Function); //true
document.write(funcO.constructor==func); //true

根据以上所说,可以明白:Object,Function,Number,String,Boolean,undefined,后面一个就不说了。前面5个typeof一下都是'function'串。例:alert( typeof Object == 'function' );和alert( Object );就明了了。(这也就是为什么XXX.constructor可以直接和她们画等号的原因。)

 ---------------------------

 一个例子

<script type="text/javascript">
  var name = "Kevin Yang";
  function sayHi(){
    alert("你好,我的名字叫" + this.name);
  }
  function Person(name){
    this.name = name;
  }
  Person.prototype.sayHello = sayHi;
  var marry = new Person("Marry");  
  marry.sayHello();
  var kevin = new Person("Kevin");
  kevin.sayHello();
script>

在上面这段代码中,我们定义了一个Person的“类”(实际上还是一个对象),然后在这个类的原型(类原型相当于C++中的静态成员变量的概念)中定义了sayHello属性,使其指向全局的sayHi对象。运行代码我们可以看到,marry和kevin都成功的向我们打了声“招呼”。

在这段代码中有两点需要思考的,一个是new我们很熟悉,但是在这里new到底做了什么操作呢?另外一个是,这里执行sayHello的时候,this指针为什么能够正确的指向marry和kevin对象呢

我们来把上面定义“类”和实例化类对象的操作重新“翻译”一下:

<script type="text/javascript">
  var name = "Kevin Yang";
  function sayHi(){
    alert("你好,我的名字叫" + this.name);
  }
  function Person(name){
    var this;
    this.name = name;
    return this;
  }
  Person.prototype.sayHello = sayHi;
  var marry = Person("Marry");  
  marry.sayHello();
  var kevin = Person("Kevin");
  kevin.sayHello();
script>

当然这段代码并不能正确执行,但是它可以帮助你更好的理解这个过程。

当我们使用new关键字实例化一个“类”对象的时候,Javascript引擎会在这个对象内部定义一个新的对象并将其存入this指针。所有此对象内部用到this的代码实际上都是指向这个新的对象。如this.name = name,实际上是将参数中的name对象赋值给了这个新创建的对象。函数对象执行完之后Javascript引擎会将此对象返回给你,于是就有 marry变量得到的对象的name为“Marry”,而kevin变量得到的对象的name属性确实“Kevin”。

原文地址:https://www.cnblogs.com/youxin/p/3219012.html