Skip to content

Instantly share code, notes, and snippets.

@RinatMullayanov
Last active August 29, 2015 14:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RinatMullayanov/0522f9689ea3ccad8f79 to your computer and use it in GitHub Desktop.
Save RinatMullayanov/0522f9689ea3ccad8f79 to your computer and use it in GitHub Desktop.
Наследование(inheritance) на основе метода предложенного Дугласом Крокфордом
// http://javascript.crockford.com/prototypal.html
// базовый вариант наследования предложенный Дугласом Крокфордом
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
// ECMASсript 3
// продвинутый вариант того что предложил Дуглас Крокфорд
// http://dmitrysoshnikov.com/ecmascript/ru-chapter-7-2-oop-ecmascript-implementation/
// http://javascript.ru/tutorial/object/inheritance
function inherit(child, parent) {
// наследование: связка прототипов
// посредством создания пустого промежуточного конструктора
var F = function() {};
F.prototype = parent.prototype; // связка, ссылка
child.prototype = new F();
child.prototype.constructor = child;
child.superproto = parent.prototype; // явная ссылка на родительский прототип, "сахар"
return child;
}
function Root(name) {
this.name = name;
}
Root.prototype.x = 1;
Root.prototype.getName = function() {
return this.name;
};
function Child(name, radius) {
this.radius = radius;
//
// вызов конструктора родителя с передачей ему параметров
Child.superproto.constructor.apply(this, arguments);
//
return this;
}
inherit(Child, Root);
Child.prototype.getSquare = function() {
return Math.PI * this.radius * this.radius;
};
var child = new Child("круг1", 10);
console.log(child.getSquare());
console.log(child.getName());
// все это аналогично Child.prototype = Object.create(Root.prototype);
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
// ECMASсript 5
// http://jsbin.com/kecar/3/edit
function Root(name, id) {
this.name = name;
this.id = id;
}
Root.prototype.x = 1;
Root.prototype.getName = function() {
return this.name;
};
Root.prototype.getId = function() {
return this.id;
};
function Child(name, id, radius) {
this.radius = radius;
// вызов конструктора родителя с передачей ему параметров
Root.apply(this, arguments);
// можно и использовать call, но тогда придется руками по именно передавать все аргументы Root.call(this, name, id);
//т.е. использование apply позволяет получить более универсальный код
return this;
}
Child.prototype = Object.create(Root.prototype); // вместо inherit
Child.prototype.getSquare = function() {
return Math.PI * this.radius * this.radius;
};
var child = new Child("круг1", 1001, 10);
console.log(child.getSquare());
console.log(child.getName());
console.log(child.getId());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment