Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
Может что-то неправильно делаю?
console.time
не поддерживается в IE9. попробуйте заменить на:var start = new Date();
for (var i = 1000000; i--;) new Foo();
alert(new Date() - start);
var start = new Date();
for (var i = 1000000; i--;) new Bar();
alert(new Date() - start);
var array = new Array('one', 'two', 'three');
array instanceof Array; // true
array instanceof Object; // true
JS проповедут прототипное ООП, вставлять классовые костыли — не гут. Учите язык и его возможности.
MyClass = function() {/* constructor */};
MyClass.prototype = new ParentClass;
они не являются детьми. и подмешивать могут произвольное число классов.
зато публичный интерфейс не захламлён мусором
исполняется код быстрее за счёт замыканий
почему ты считаешь одну реализацию правильнее другой?
alert([].hasOwnProperty('push')); // false
могут быть без лишнего геморроя отданы в качестве колбэка.
var a = [];
a.hasOwnProperty('push'); // false push in prototype
a.pushh = function () {};
a.hasOwnProperty('pushh'); // true pushh is own property
var Foo = function() {
this.method1 = function(){};
}
var Bar = function() {};
Bar.prototype.method1 = function(){};
такое, что оно компенсирует затраты памяти и время создания?var foo = (function () {
var y = 20;
return function () {
alert(y);
};
})();
foo(); // 20
alert(foo.__parent__.y); // 20
foo.__parent__.y = 30;
foo(); // 30
Во-вторых приватные методы — траты памяти. В-третьих приватные методы сложно сразу найти в коде и они искривляют структуру программы. Foo.prototype._smthPrivate = function () {};
var Foo = function() {
this.method = function(){};
};
var bar = new Foo;
var qux = new Foo;
bar.method.qwe = 1;
qux.method.qwe = 2;
console.log(bar.method.qwe); // 1
console.log(qux.method.qwe); // 2
alert('Start');
var Bar = function() {
this.a1 = 1;
this.a2 = {};
this.a3 = [];
this.a4 = '0';
this.a5 = false;
this.a6 = /\s/ig;
this.a7 = window;
this.a8 = .1;
this.a9 = 100;
};
Bar.prototype.method1 = function(){ this.a1 = this.a1 * this.a8 };
Bar.prototype.method2 = function(){ this.a2 = this.a2 + this.a7 };
Bar.prototype.method3 = function(){ this.a3 = this.a3 - this.a6 };
Bar.prototype.method4 = function(){ this.a4 = this.a4 / this.a5 };
Bar.prototype.method5 = function(){ this.a5 = this.a5 || this.a9 };
Bar.prototype.method6 = function(){ this.a6 = this.a6 && this.a4 };
Bar.prototype.method7 = function(){ this.a7 = this.a7 + this.a3 };
Bar.prototype.method8 = function(){ this.a8 = this.a8 - this.a2 };
Bar.prototype.method9 = function(){ this.a9 = this.a9 * this.a1 };
var data = [];
for (var i = 1000000; i--;) {
data.push(new Bar());
}
// чтобы было все честно
window.setTimeout(function () {
data[~~(data.length * Math.random())]();
}, 10000000);
alert('Start');
var Bar = function() {
this.a1 = 1;
this.a2 = {};
this.a3 = [];
this.a4 = '0';
this.a5 = false;
this.a6 = /\s/ig;
this.a7 = window;
this.a8 = .1;
this.a9 = 100;
this.method1 = function(){ this.a1 = this.a1 * this.a8 };
this.method2 = function(){ this.a2 = this.a2 + this.a7 };
this.method3 = function(){ this.a3 = this.a3 - this.a6 };
this.method4 = function(){ this.a4 = this.a4 / this.a5 };
this.method5 = function(){ this.a5 = this.a5 || this.a9 };
this.method6 = function(){ this.a6 = this.a6 && this.a4 };
this.method7 = function(){ this.a7 = this.a7 + this.a3 };
this.method8 = function(){ this.a8 = this.a8 - this.a2 };
this.method9 = function(){ this.a9 = this.a9 * this.a1 };
};
var data = [];
for (var i = 1000000; i--;) {
data.push(new Bar());
}
// чтобы было все честно
window.setTimeout(function () {
data[~~(data.length * Math.random())]();
}, 10000000);
Видимо совсем идиоты…
alert('Start');
var bar = function() {
this.a1 = 1;
this.a2 = {};
this.a3 = [];
this.a4 = '0';
this.a5 = false;
this.a6 = /\s/ig;
this.a7 = window;
this.a8 = .1;
this.a9 = 100;
var a = {};
a.method1 = function(){ this.a1 = this.a1 * this.a8 };
a.method2 = function(){ this.a2 = this.a2 + this.a7 };
a.method3 = function(){ this.a3 = this.a3 - this.a6 };
a.method4 = function(){ this.a4 = this.a4 / this.a5 };
a.method5 = function(){ this.a5 = this.a5 || this.a9 };
a.method6 = function(){ this.a6 = this.a6 && this.a4 };
a.method7 = function(){ this.a7 = this.a7 + this.a3 };
a.method8 = function(){ this.a8 = this.a8 - this.a2 };
a.method9 = function(){ this.a9 = this.a9 * this.a1 };
return a;
};
var data = [];
for (var i = 1000000; i--;) {
data.push(bar());
}
// чтобы было все честно
window.setTimeout(function () {
data[~~(data.length * Math.random())]();
}, 10000000);
var Foo = function() {
this.a = 0;
this.method = function() { this.anotherMethod(); };
this.anotherMethod = function() { this.a++; };
var p = 0;
this.increaseP = function () { p++; }
this.getP = function() { return p; }
};
var Bar = function() {
this.a = 0;
this._p = 0;
};
Bar.prototype.method = function() { this.anotherMethod(); };
Bar.prototype.anotherMethod = function() { this.a++; };
Bar.prototype.increaseP = function() { this._p++; };
Bar.prototype.getP = function() { return this._p; };
var foo = new Foo;
var bar = new Bar;
/**
* Firefox 3.5
* foo : 197ms
* bar : 195ms
* fooP: 166ms
* barP: 146ms
* Chrome 8
* foo : 78ms
* bar : 79ms
* fooP: 86ms
* barP: 83ms
*/
console.time('foo');
for (var i = 100000; i--;) foo.method();
console.timeEnd('foo');
console.time('bar');
for (var i = 100000; i--;) bar.method();
console.timeEnd('bar');
console.time('fooP');
for (var i = 100000; i--;) foo.increaseP();
console.timeEnd('fooP');
console.time('barP');
for (var i = 100000; i--;) bar.increaseP();
console.timeEnd('barP');
console.log(foo.a, foo.getP(), bar.a, bar.getP(), bar._p);
то всегда можно приписать MyAnotherClass.prototype= MyClass.prototype
Parent = function(){};
Child = function(){};
Parent.prototype= Child.prototype;
var parent = new Parent;
console.log(parent instanceof Child); // true
newClass.$constructor = Class;
newClass.prototype.$constructor = newClass;
newClass.prototype.parent = parent;
var Utils = {
inherit: function (child, parent) {
function F() {}
F.prototype = parent.prototype;
child.prototype = new F();
child.prototype.constructor = child;
child.superproto = parent.prototype;
return child;
}
};
var Foo = function () {alert('Foo')};
Foo.prototype.a = function () { alert('1') };
var Bar = function () {alert('Bar')};
Utils.inherit(Bar, Foo);
Bar.prototype.a = function () {
Bar.superproto.a.call(this);
alert('2');
};
var bar = new Bar();
bar.a();
Прототипное: own -> proto -> proto -> proto -> null
Классовое (абстрактно): own -> class -> superclass -> superclass -> null.
var a = {};
var b = [];
// both are objects
alert([typeof a, typeof b]); // "object", "object"
// but have different classification tags
var getClass = Object.prototype.toString;
alert([getClass.call(a), getClass.call(b)]); // "[object Object]", "[object Array]"
var point = {x: 1, y: 2};
var a = {x: 1, y: 2};
var b = {x: 3, y: 4};
var c = {x: 5, y: 6};
function makePoint(x, y) {
return {
x: x,
y: y
};
}
var a = makePoint(1, 2);
var b = makePoint(3, 4);
var c = makePoint(5, 6);
makePoint.prototype = {
constrcutor: makePoint
};
function makePoint(x, y) {
return {
__proto__: makePoint.prototype,
x: x,
y: y
};
}
a.constructor // a.constructor -> not found, a.__proto__.constructor -> found == makePoint.
function Point() { // no "make"
this.x = x;
this.y = y;
}
var a = new Point(1, 2);
var b = new Point(3, 4);
var c = new Point(5, 6);
a.constructor // Point
показать его особенности, его своеобразие, его красоту
«классы в языке — это возможность генерировать и классифицировать»… ну, тогда везде они… классы эти.
всё-таки продолжаю бороться со сложностью — классов в js нет ;-)
Обёртки для создания классов: зло или добро?