Skip to content

Instantly share code, notes, and snippets.

@MarkBennett
Created January 18, 2011 21:04
Show Gist options
  • Save MarkBennett/785144 to your computer and use it in GitHub Desktop.
Save MarkBennett/785144 to your computer and use it in GitHub Desktop.
JavaScript Objects
function Human(name, age) {
this.name = name;
this.age = age;
}
bob = new Human("bob", 30);
bob.name; // "bob"
bob.age; // 30
function Human(name, age) {
this.name = name;
this.age = age;
}
Human.prototype; // {}
Human.prototype.sayHello = function() {
return "Hi, I'm " + this.name + "!";
};
Human.sayHello; // undefined
function foo(a, b) {
return a * b;
}
foo(3, 4); // 12
foo.a = "abc";
foo.a; // "abc"
foo.bar = function() {
"baz"
};
foo.bar(); // "baz"
{} == new Object();
b = {
"name":"Bob",
age: 30
};
b.name; // "Bob"
b["age"]; // 30
b.breathes = "air";
b.breathes; // "air"
b = {
"name":"Bob",
age: 30
};
b.child = {
age: 5
}
b.child.age; // "age"
a = {};
a.constructor; // function Object() { ... }
b = new Object();
b.constructor; // function Object() { ... }
function Human() {
this.breathes = "air";
}
bob = new Human();
bob.breathes; // "air"
bob.constructor; // function Human() { ... }
bob = new Human("bob", 30);
bob.constructor; // function Human() { ... }
bob.constructor.prototype; // { sayHello: ... }
bob.sayHello(); // "Hi, I'm Bob!"
function Animal() {
this.breathes = "air";
}
function Human(name, age) {
this.name = name;
this.age = age;
}
Human.prototype = new Animal();
bob = new Human("bob", 30);
bob.breathes; // "air"
bob.constructor; // function Animal() { ... }
Human.prototype.constructor = Human;
bob.constructor; // function Human() { ... }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment