März 13th, 2006

JavaScript: typeof vs. instanceof

Posted by frank in AJAX

Soeben habe ich noch etwas bemerkenswertes festgestellt. Laut JavaScript ist eine einfache Function automatisch ein Objekt.

Folgender Code soll es verdeutlichen:


function o() {
}

var t = new o();

alert((typeof o == "function") ? "true" : "false");
alert((typeof t == "function") ? "true" : "false");
alert((o instanceof Object) ? "true" : "false");
alert((t instanceof Object) ? "true" : "false");

Dieser Code gibt folgendes aus: true, false, true, true

Es sollte also nie eine function auf “Object” mit instanceof geprüft werden.

2 Responses to ' JavaScript: typeof vs. instanceof '

Subscribe to comments with RSS or TrackBack to ' JavaScript: typeof vs. instanceof '.

  1. patrick e. said,

    on Mai 9th, 2007 at 1:56 am

    objectName = new objectType(param1 [,param2] …[,paramN])

    http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Operators:Special_Operators:new_Operator

  2. f.o. said,

    on März 15th, 2009 at 8:16 pm

    https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Function#Properties

Leave a reply

:mrgreen: :neutral: :twisted: :shock: :smile: :???: :cool: :evil: :grin: :oops: :razz: :roll: :wink: :cry: :eek: :lol: :mad: :sad: