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
constructorwill be called with.
Description
Creating a user-defined object requires two steps:
- Define the object type by writing a function.
- 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:
- A new object is created, inheriting from
foo.prototype. - The constructor function
foois called with the specified arguments andthisbound to the newly created object.new foois equivalent tonew foo(), i.e. if no argument list is specified,foois called without arguments. - The object returned by the constructor function becomes the result of the whole
newexpression. 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”。
js Function 加不加new 详解的更多相关文章
- ext.js的mvc开发模式详解
ext.js的mvc开发模式详解和环境配置 在JS的开发过程中,大规模的JS脚本难以组织和维护,这一直是困扰前端开发人员的头等问题.Extjs为了解决这种问题,在Extjs 4.x版本中引入了MVC开 ...
- 微信JS接口汇总及使用详解
这篇文章主要介绍了微信JS接口汇总及使用详解,十分的全面.详尽,包含分享到朋友圈,分享给朋友,分享到QQ,拍照或从手机相册中选图,识别音频并返回识别结果,使用微信内置地图查看位置等接口,有需要的小伙伴 ...
- js对象浅拷贝和深拷贝详解
js对象浅拷贝和深拷贝详解 作者:i10630226 字体:[增加 减小] 类型:转载 时间:2016-09-05我要评论 这篇文章主要为大家详细介绍了JavaScript对象的浅拷贝和深拷贝代码,具 ...
- JS中的event 对象详解
JS中的event 对象详解 JS的event对象 Event属性和方法:1. type:事件的类型,如onlick中的click:2. srcElement/target:事件源,就是发生事件的 ...
- js中鼠标滚轮事件详解
js中鼠标滚轮事件详解 (以下内容部分内容参考了http://adomas.org/javascript-mouse-wheel/ ) 之前js 仿Photoshop鼠标滚轮控制输入框取值中已使用 ...
- js中中括号,大括号使用详解
js中中括号,大括号使用详解 一.总结 一句话总结:{ } 是一个对象,[ ] 是一个数组 1.js大括号{}表示什么意思? 对象 { } 大括号,表示定义一个对象,大部分情况下要有成对的属性和值,或 ...
- amazeui中的js插件有哪些(详解功能)
amazeui中的js插件有哪些(详解功能) 一.总结 一句话总结: 二.amazeui中的js插件有哪些 1.UI 增强 警告框Alert 按钮交互Button 折叠面板Collapse 下拉组件D ...
- C编译器、链接器、加载器详解
摘自http://blog.csdn.net/zzxian/article/details/16820035 C编译器.链接器.加载器详解 一.概述 C语言的编译链接过程要把我们编写的一个c程序(源代 ...
- JS函数动作分层结构详解及Document.getElementById 释义 js及cs数据类型区别 事件 函数 变量 script标签 var function
html +css 静态页面 js 动态 交互 原理: js就是修改样式, 比如弹出一个对话框. 弹出的过程就是这个框由disable 变成display:enable. 又或者当鼠标指向 ...
随机推荐
- NET Core,Ubuntu运行
NET Core,如何开发跨平台的应用并部署至Ubuntu运行 之前写了一篇博文宣布Rabbit Rpc跨平台了“拥抱.NET Core,跨平台的轻量级RPC:Rabbit.Rpc”,在过程中尝试了如 ...
- word-break与word-wrap
本文列举了兼容 IE 和 FF 的换行 CSS 推荐样式,详细介绍了word-wrap同word-break的区别. 兼容 IE 和 FF 的换行 CSS 推荐样式 最好的方式是 以下是引用片段: ...
- samba服务器上文件名大小写
samba服务器上文件名大小写 如果给HP_UX配置samba之后,通过windows访问有时候会发现文件名大小写不对时,请注意下述配置信息是否正确.在/etc/opt/samba/smb.conf中 ...
- android 百度最新地图sdk包怎么去除 放大缩小按钮
// 隐藏缩放控件 int childCount = mMapView.getChildCount(); View zoom = null; ; i < childCount; i++) { V ...
- 增强Delphi.RemObject.DataAbstract的脚本功能:多数据库同时操作
我们知道,通过Schema,一个DataAbstracService对应一个数据库:一个服务器可以包含多个DataAbstracService,从而实现对多个数据库的操作.通过事件处理我们可以在一个D ...
- Android中获取系统的时间
activity代码 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); set ...
- 将文件从数据库(MySQL)中进行读取
package com.play; import java.io.FileOutputStream; import java.io.OutputStream; import java.sql.Blob ...
- jbpmAPI-2
2.1. Downloads 所有的版本都可以从SourceForge下载.选择您想要下载的版本,然后选择你想要工件: https://sourceforge.net/projects/jbpm/fi ...
- LNMP安装包sh脚本
Xshell 5 (Build 0719) Copyright (c) 2002-2015 NetSarang Computer, Inc. All rights reserved. Type `he ...
- Python之路Day17
算法:冒泡排序.插入排序.快速排序.堆排序 冒泡排序 #! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Q1mi& ...