【发布时间】:2014-04-09 19:38:59
【问题描述】:
以下代码用作 JavaScript 中的继承方法,但我在遵循代码时遇到问题,特别是“this”的上下文,因此我将问题添加为代码 cmets。提前感谢您的启发。
var Class = function(){
var klass = function(){
//Is "this" referring to the Class class or Klass class?
//Why is "this" being applied to "this.init"? Isn't this default behavior?
//Are they both the same "this"?
this.init.apply(this, arguments);
};
klass.prototype.init = function(){};
return klass;
};
var Person = new Class;
Person.prototype.init = function(){
// Called on Person instantiation
};
// Usage:
var person = new Person;
抱歉,如果我误解了整件事。
【问题讨论】:
-
您应该阅读
apply的作用。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
MDN 对
this的工作原理有相当广泛的解释:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript class inheritance this