ITeye博客

用new创建自定义对象时的疑问

kino · 2008-09-26 11:15 · javascript · Web前端 · F# · prototype · Markdown

我昨天发现了js的一些奇怪问题,当用new操作符创建自己的对象时。不知有人知道原因吗?

1、我们可以用function创建构造函数,然后用new生成自己的对象。

function book(){
    this.tip="I'm a book";
}
var myBook = new book();

 

上面代码没什么疑问,会生成一个新的对象,myBook来引用它,这个对象有一个属性tip,值为"I'm a book"

2、当我们在构造函数中加入返回语句时

function book(){
    this.tip="I'm a book";
    return {};
}
var myBook = new book();

 

上面在构造函数的最后返回了一个空对象,这时的myBook就是一个空对象,不拥有任何属性。‘this.tip="I'm a book"’就像没起作用。

3、当我们返回的是一个字符串字面量时(数字也可以)

function book(){
    this.tip="I'm a book";
    return "I'm a string";
}
var myBook = new book();

 

按道理推测,这时的myBook就该引用的是字符串对象"I'm a string",但事实上是myBook和1中的一样,引用了一个对象,该对象有一个属性tip,值为"I'm a book",这时的return为什么没用了 。

4、当我们以另一种方式返回一个字符串时(数字一样)

function book(){
    this.tip="I'm a book";
    return new String("I'm a string");
}
var myBook = new book();

 

这时的myBook引用的就是字符串"I'm a string",这个和3中有什么不同?

所以,我想知道new操作符做了些什么,机制又是如何的?

评论(3)

  1. #3 楼 · jimmyideal · 2008-09-26 16:27

    字符串字面量应该就是直接反映内存中的值,它不是一个对象; new String()产生的是内建的String对象的实例。 但是,为什么又有这种写法:"string a".charAt(i) ? 这是由于属性操作符(.)帮我们转换成String Object,ECMAScript Language Specification 11.2.1 Property Accessors :

    The production MemberExpression : MemberExpression [ expression ] is evaluated as follows:

    1. Evaluate MemberExpression.

    2. Call GetValue(Result(1)).

    3. Evaluate Expression.

    4. Call GetValue(Result(3)).

    [b]5. Call ToObject(Result(2)).[/b]

    1. Call ToString(Result(4)).

    2. Return a value of type Reference whose base object is Result(5) and whose property name is Result(6).

  2. #2 楼 · kino · 2008-09-26 13:48

    谢谢楼上的解释。 我还有一个疑问就是字符串字面量和new出来的字符串有何区别?是不是不把字符串字面量当作对象看待?

  3. #1 楼 · jimmyideal · 2008-09-26 11:44

    来自ECMAScript Language Specification,构造函数的执行过程

    When the [[construct]] property for a Function object F is called, the following steps are taken:
    
    1. Create a new native ECMAScript object.
    
    2. Set the [[class]] property of Result(1) to "Object".
    
    3. Get the value of the prototype property of F.
    
    4. If Result(3) is an object, set the [[prototype]] property of Result(1) to Result(3).
    
    5. If Result(3) is not an object, set the [[prototype]] property of Result(1) to the original Object prototype object as described in 15.2.3.1.
    
    6. Invoke the [[call]] property of F, providing Result(1) as the this value and providing the argument list passed into [[construct]] as the argument values.
    
    7. If Type(Result(6)) is Object then return Result(6).
    
    8. Return Result(1).
    

    构造函数执行过程会创建一个对象。如果函数有返回值且为对象,则做为new操作符的结果返回;否则返回新创建的对象。3,4的区别在于,4返回String对象。

评论功能维护中,当前仅展示历史评论。