JS Core 1_4
Prototype
object
proto {}
proto {}
prop1
prop2
prop3
Prototype chain
OBJECT
FUNCTIONS
ARRAYS
Function constructors
(functions that are used
to create an objects)
var elephant = new Animal();
function Animal () {
this.type = 'elephant';
this.name = 'Cute';
return 'hey';
}
typeof new Animal(); // Object
typeof Animal(); // String
function Animal (name, type) {
this.name = name;
this.type = type;
}
var obj1 = new Animal('Jake', 'Cat');
var obj2 = new Animal('Doggy', 'Dog');
.prototype
Function
code
name
prototype
function Animal(name, type) {
this.name = name;
this.type = type;
}
var cat_obj = new Animal('Jake', 'Cat');
var dog_obj = new Animal('Doggy', 'Dog');
Animal.prototype.present_me = function() {
return 'Hello i am ' + this.name + ' ' + this.type;
};
constructor convention
function Animal () {...}
function animal () {...}
Built-in constructors
use prototype to add method
Array object
var arr = ['one', 'two', 'three'];
for (var prop in arr) {
console.log(prop + ': ' + arr[prop]);
}
Array.prototype.myprop = '100500';
for (var prop in arr) {
console.log(prop + ': ' + arr[prop]);
}
Pure prototype inheritence
var group = {
count: 21,
method1: function() {
return this.count;
}
}
var group1 = Object.create(group);
function Person(name) {
this.name = name;
}
Person.prototype.present = function() {
console.log('Hello, I am ' + this.name);
}
function Men() {
Person.apply(this, arguments);
this.hobby = 'Football';
}
Men.prototype = Object.create(Person.prototype);
Men.prototype.constructor = Men;
Men.prototype.getDrunk = function() {
console.log('Give me 10 beers, and lets go ' + this.hobby);
}
function Women() {
Person.apply(this, arguments);
this.color = 'red';
}
Women.prototype = Object.create(Person.prototype);
Women.prototype.constructor = Women;
Women.prototype.speak = function() {
console.log('my favorite color is ' + this.color);
}
JS Core 1_4
By Mikki Churilov
JS Core 1_4
- 1,062