当前位置: 代码迷 >> Web前端 >> new毕竟new出了什么
  详细解决方案

new毕竟new出了什么

热度:367   发布时间:2012-10-08 19:54:56.0
new到底new出了什么
犀牛书9.1写道:

The new operator must be followed by a function invocation. It creates a new object, with no properties and then invokes the function, passing the new object as the value of the this keyword. A function designed to be used with the new operator is called a constructor function or simply a constructor. A constructor's job is to initialize a newly created object, setting any properties that need to be set before the object is used.

可以看到,javascript里的new和java里的new区别还是很大的,不要理解成同一个东西就对了。

实际上,任何function都可以跟在new后面,比如说:
function test() {
    var o = new Con("hello 2011");
}

function Con(msg) {
    alert("this is the message: " + msg);
}

虽然Con的本意并不是一个构造函数,但是在语法上却是没有错误的。执行test()函数,实际上就是先创建了一个普通的Object,然后执行Con()函数而已。不过这个时候Con()函数被视为Object的一个方法,相当于o.Con(msg)。所以这个时候函数体内的this就是o。(当然上面的例子里,函数体内并没有this)
  相关解决方案