вопрос по созданию функции
добрый день, всем!.. подскажите, пжлст, как решить задачу:
Есть объект Person (name, age, method), и есть объект Student, который наследует Person и имеет свой method2. 1.Нужно реализовать функцию type(), которая принимает объект Student или Person и возвращает его тип, НЕ используя оператор instanceof, а используя проверку наличия свойств/методов объектов. 2.Модифицировать функцию так, что она не принимает объект, а оперирует с объектом this. Функция объявляется вне контекста, но вызывается на определенном объекте при помощи call/apply/bind. Спасибо! |
DennisMatveyev,
Не вижу ваших попыток решения проблемы. http://javascript.ru/forum/misc/3706...-otvetili.html |
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.method = function() {
alert(this.name + this.age);
};
function Student(name, age) {
Person.apply(this, arguments);
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.method2 = function() {
alert("Bla-bla-bla");
};
var vasya = new Person('Василий', 25);
var petya = new Student('Петя', 18);
function type() {
(this.method2 !== undefined) ? alert('Student') : alert('Person');
}
type.call(vasya);
type.call(petya);
|
getType=function(object){return object? object.type : this.type}
Person={
type: "Person",
extend: function(o){
for(var i in o) {if(!o.hasOwnProperty(i)) return this; this[i]=o[i]} return this
},
clone: function(){
return Object.create(this)
},
getType: getType,
getData: function(){return this.name+" "+this.age}
}
Student=Person.clone().extend({
type: "Student",
getFuckingData: function(){return "I am "+this.name+" and I'm motherfucker"}
})
john=Student.clone().extend({name: "John", age: 19})
with(console){
log(getType(john))
log(getType.call(john))
log(getType.apply(john))
log(getType.bind(john)())
log(john.getType())
log(john.getData(), john.getFuckingData())
}
// ::: Student
// ::: Student
// ::: Student
// ::: Student
// ::: Student
// ::: John 19 I am John and I'm motherfucker
|
класс.... спасибо большое!:victory:
|
| Часовой пояс GMT +3, время: 05:15. |