Remember: typeoffor literals.
typeof undefined === "undefined"
typeof 5 === "number"
typeof true === "boolean"
typeof "" === "string"
typeof {} === "object"
typeof [] === "object"
typeof function { } === "function"
typeof null === "object"
instanceofdistinguishes when something has “functions” (note that where typeof checks the string, "object"instanceof checks directly for the functions Object:
{} instanceof Object
function {} instanceof Object
function {} instanceof Function
[] instanceof Object
[] instanceof Array
As you can see, typeof says === "function"and !== "object": this can be misleading because the function is also an object. This is when instanceof comes into play.
Now, when you write a constructor, the constructed object is also an instance of your function:
function Example { }
var ex = new Example();
typeof Example === "function"
typeof ex === "object"
ex instanceof Object
ex instanceof Example
, , typeof :
function DerivedExample { }
DerivedExample.prototype = new Example();
var ex1 = new DerivedExample();
typeof DerivedExample === "function"
typeof ex1 === "object"
ex1 instanceof Object
ex1 instanceof Example
ex1 instanceof DerivedExample
, javaScript typeof, instanceof. , , .
- ( , CoffeeScript):
typeof new Number(5) === "object"
new Number(5) instanceof Object
new Number(5) instanceof Number
typeof new Boolean("true") === "object"
new Boolean("true") instanceof Object
new Boolean("true") instanceof Boolean
typeof new String("") === "object"
new String("") instanceof Object
new String("") instanceof String
window:
.
( ), "use strict" "", undefined.
function world() {
}
world();
, , :
var hello = {
world: function () {
}
};
hello.world();
, :
function Hello() { }
Hello.prototype.world = function () {
};
var ex = new Hello();
ex.world();
, call apply:
var ex = { };
function Example() {
}
Example();
Example.call(ex);
Example.apply(ex);