首页 > JavaScript > JavaScript 自定义对象的constructor属性有用吗?
2010四月16

JavaScript 自定义对象的constructor属性有用吗?

前面的文章我们提到过每个实例化的对象都有一个指向其构造函数的constructor属性。但是这个属性真的有用吗?

看JavaScript类式继承的时候,都会将子类prototype对象的constructor属性给修正回来,但是修正回来的意义何在呢?实在找不出来有何地方需要这个属性。

<html>
    <head>
        <title>js extend</title>
    </head>
    <body>
        <script type="text/javascript">
            function Person(name){
                this.name = name;
            }
            Person.prototype.getName = function(){
                return this.name;
            }
           
            function Author(name,books){
                Person.call(this,name);
                this.books = books;
            }
           
            Author.prototype = new Person();
                        //这句就是起修正的作用
                        //Author.prototype.constructor = Author;
            Author.prototype.getBooks = function(){
                return this.books;
            }
           
            var author = new Author('simaopig','js');
           
            //simaopig
            alert(author.getName());
            //js
            alert(author.getBooks());
            //Person 函数结构
            alert(author.constructor);
            //true
            alert(author instanceof Person);
            //true
            alert(author instanceof Author);
        </script>
    </body>
</html>

无论我是否修正其constructor属性,instanceof 的结果都是两个均为true,也就是说我们的继承是实现了的。因为Author本身也是Person的子类。所以很是不解,留此文,待日后询问高手。

文章作者:simaopig
本文地址:http://www.xiaoxiaozi.com/2010/04/16/1746/
版权所有 © 转载时必须以链接形式注明作者和原始出处!

6 Responses to “JavaScript 自定义对象的constructor属性有用吗?”

  1. #1 lenel 回复 | 引用 Post:2010-04-16 23:30

    我猜修正是有用的吧.呵呵.比如调用父类的构造函数啊.
    XClass.superclass.constructor.apply(this, arguments);
    另外别人用你的代码,可能想知道正确的constructor是啥呢

    [回复]

  2. #2 simaopig 回复 | 引用 Post:2010-04-17 10:42

    @lenel
    嗯。用extend方法(自己写的),调用父类的构造函数,可以使其在继承时里面不含有父类的名称这点确实是有用的。呵呵。

    [回复]

  3. #3 lenel 回复 | 引用 Post:2010-04-17 15:20

    我这里是这个印象”类的实例的constructor其实是指向类的prototype属性的constructor”,想着备不住可以利用这个做点什么,实际上却很少用到.

    js蹩脚的oo,constructor和instanceof必然会毁掉一个,还好修正constructor是可行的,而修正instanceof的结果是妄想.但似乎修正constructor会影响某些浏览器下hasOwnProperty的结果.反正烦的很.

    推荐”Javascript对象真经”,看过比较多类似的内容,但那张图画的着实不错.
    http://w3er.com/javascript/master-javascript-object-system/

    [回复]

  4. #4 simaopig 回复 | 引用 Post:2010-04-17 16:59

    @lenel
    呵,好的。谢谢分享。我去看一下。3Q。

    [回复]

  5. #5 可乐加糖 回复 | 引用 Post:2010-04-28 19:07

    :lol: :lol:

    哈哈,这个问题,你要仔细看看 JavaScript 原型链的文章,就能解释为什么
    b.prototype = new a();
    这样的意义了.

    [回复]

  6. #6 simaopig 回复 | 引用 Post:2010-04-29 09:25

    @可乐加糖
    呵呵。在抄完《JavaScript 高级程序设计 第二版》的一些内容后,已经理解了。这个是之前写的,呵呵。 :smile:

    [回复]

发表评论

:wink: :twisted: :roll: :oops: :mrgreen: :lol: :idea: :evil: :cry: :arrow: :?: :-| :-x :-o :-P :-D :-? :) :( :!: 8-O 8)