SitePoint Sponsor

User Tag List

Results 1 to 6 of 6

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Feb 2004
    Location
    Third Stone From The Sun
    Posts
    82
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    instanceof vs isPrototypeOf

    When should I use instanceof vs isPrototypeOf() ?

    Code:
    function A(){}
    function B(){}
    function C(){}
    
    B.prototype = new A();
    C.prototype = new B();
    
    var c = new C(); 
    (c instanceof A); // true
    A.prototype.isPrototypeOf( c ); // true
    C.prototype.isPrototypeOf( c ); // true
    (c instanceof C); // true
    My outdated site is down for a while now.

  2. #2
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Good question!

  3. #3
    SitePoint Enthusiast
    Join Date
    Feb 2004
    Location
    Third Stone From The Sun
    Posts
    82
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Am I overthinking this?

    I'm just wondering if there is a reason to use one instead of another.

    I can't think of any. (goto 0);

    Maybe I need a break;
    My outdated site is down for a while now.

  4. #4
    SitePoint Guru
    Join Date
    Apr 2007
    Posts
    813
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    is that javascript standards? I have never used it before

  5. #5
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    @DHTML Kitchen:
    I also tried to think of a situation where one would be more appropriate than the other... but I didn't come up with anything

    @SimplyFu:
    Yes, instanceof is an operator and was implemented in JavaScript 1.4. isPrototypeOf is a method of the Object object and "I think" it was implemented in JavaScript 1.5. That alone may be reason enough to use instanceof instead of isPrototypeOf.

  6. #6
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you want to find out if the object is an instance of Array, for example, it seems simpler to use instanceof than to see if it's prototype is the same prototype as the Array prototype.

    I nearly always use if(obj.constructor==Array), because you can use obj.constructor to pass the constructor function, but for a simple test instanceof would be sufficient.

    The only time I ever use isPrototypeOf is in debugging, when I need to track a method that is called or applied on a variety of custom objects.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •