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. 又或者当鼠标指向 ...
随机推荐
- 国内外主流BI厂商对比
BI(Business Intelligence),即商业智能或者商务智能,它是一套完整的解决方案,用来将企业中现有的数据进行有效的整合,快速准确的提供报表并提出决策依据,帮助企业做出明智的业务经营决 ...
- Sql:查看数据库表和表结构的语句
T-sql 显示表结构和字段信息的sql语句: exec sp_help tablename; ~~使用存储过程 sp_help 显示数据库包含哪些表的sql语句: use yourDBname;se ...
- C++中struct和class的总结
一.在语法上的一些区别 由于C++是从C发展而来,C++中的struct更多的是去做了兼容的C的部分.在语法层面他们有以下的区别: 1. struct中所有的成员是是public,也就是说你可以对一个 ...
- 在LINUX的命令提示符及CMD命令提示符中显示时间
用途之一是可以查看某个命令或程序的执行时间. 一.CMD中显示时间设置 参数说明: $P:当前路径 $G:>(大于号) $T:当前时间,精确到0.01s 实验如下: C:\Users\g4-10 ...
- php单元測试
你是否在程序开发的过程中遇到下面的情况:当你花了非常长的时间开发一个应用后,你觉得应该是大功告成了,可惜在调试的时候,老是不断的发现bug,并且最可怕的是,这些bug是反复出现的,你可能发现这些bug ...
- 解决Windows 7下IE11无法卸载、无法重新安装,提示安装了更新的IE版本
2013年12月14日 iefans 有用户反馈在Windows 7系统上安装IE11时发现安装程序似乎出了问题,等待了很长时间都没有响应之后就断开了电脑的电源.之后IE11浏览器虽然能使用,却无法安 ...
- CSS的float与clear
首先要知道,div是块级元素,在页面中独占一行,自上而下排列,也就是传说中的流.如下图: 可以看出,即使div1的宽度很小,页面中一行可以容下div1和div2,div2也不会排在div1后边,因为d ...
- c#程序添加其他网站的webservice引用。
前言: 有A网站,B网站两个网站独立运行.某一天,需要两个网站进行合作来完成一件事,比如用A网站接收一些数据进行处理,存入中转数据库,B网站定时去取数据进入自己的系统进行处理. 可能我们会先想到在B网 ...
- UI界面
http://www.uimaker.com/uimakerhtml/uidesign/uisoft/2016/0323/122862.html http://www.uimaker.com/uima ...
- Setting property 'source' to 'org.eclipse.jst.jee.server [问题点数:40分]
链接地址:http://bbs.csdn.net/topics/390131469 警告: [SetContextPropertiesRule]{Context} Setting property ' ...