У меня есть этот код:
var first = function() {
this.loc = '1';
this.test = function() {
console.log('first ' + this.loc);
}
}
var second = function() {
var me = this;
this.loc = '2';
this.test = function() {
console.log('second ' + this.loc);
Object.getPrototypeOf(me).test.call(me);
}
}
second.prototype = new first();
var third = function() {
var me = this;
this.loc = '3';
this.test = function() {
console.log('third ' + this.loc);
Object.getPrototypeOf(me).test.call(me);
}
}
third.prototype = new second();
var t = new third();
t.test();
Это выведет:
third 3
second 3
first 2
Как я могу сделать вывод:
third 3
second 3
first 3
Поэтому я хочу переопределить значение loc первого класса последним унаследованным классом.
3 ответа
Измените thisArg
(подпись fun.call(thisArg[, arg1[, arg2[, ...]]])
) для вызова объектной функции second
с me
на this
:
...
var second = function() {
var me = this;
this.loc = '2';
this.test = function() {
console.log('second ' + this.loc);
Object.getPrototypeOf(me).test.call(this); // <--
}
}
...
Как это происходит.
В первый раз функция test()
вызывается при выдаче экземпляра third
"third 3"
Затем функция test
вызывается из экземпляра second
(являющегося прототипом third
) в том же экземпляре third
с помощью Object.getPrototypeOf(me).test.call(me);
Когда функция test
выполняется, ключевое слово this
должно указывать на экземпляр third
и передаваться для дальнейшего вызова test()
Вы делаете некоторые интересные вещи с наследованием, смешивая прототип и назначения this.x. Интересно, следующий фрагмент кода будет делать то, что вы хотите вместо этого:
var first = function( num ){
this.num = num;
}
first.prototype.test = function(){ console.log("value " + this.num); }
// test it
var x = new first(10);
x.test();
var second = function( ){
first.apply(this, arguments);
}
second.prototype = new first();
second.prototype.test2 = function(){ console.log("second " + this.num) };
// test it
var y = new second( 20 );
y.test()
var third = function( ){
second.apply(this, arguments);
}
third.prototype = new second();
second.prototype.test3 = function(){ console.log("third " + this.num) };
// test it
var z = new third( 30 );
z.test()
z.test2()
z.test3()
this
указатель на second
фактически равен third.prototype
. поэтому установите свойство loc
для second
(third.prototype
)
var first = function() {
this.loc = '1';
this.test = function() {
console.log('first ' + this.loc);
}
}
var second = function() {
var me = this;
this.loc = '2';
this.test = function() {
console.log('second ' + this.loc);
Object.getPrototypeOf(me).test.call(me);
}
}
second.prototype = new first();
var third = function() {
var me = this;
this.loc = '3';
this.test = function() {
console.log('third ' + this.loc);
Object.getPrototypeOf(me).test.call(me);
}
}
third.prototype = new second();
third.prototype.loc = 3;
var t = new third();
t.test();
Похожие вопросы
Новые вопросы
javascript
По вопросам программирования на ECMAScript (JavaScript / JS) и его различных диалектах / реализациях (кроме ActionScript). Включите все соответствующие теги в свой вопрос; например, [node.js], [jquery], [json] и т. д.