令人困惑的JavaScript语句:“ var x = new this();” [英] Confusing JavaScript statement: "var x = new this();"
问题描述
我以为我了解JavaScript原型对象以及[[proto]]的概念,直到看到一些有关类继承的帖子。
I thought I understood the concept of the JavaScript prototype object, as well as [[proto]] until I saw a few posts regarding class inheritance.
首先, http://amix.dk/blog/viewEntry/19038
请参阅实现部分:
var parent = new this('no_init');
还有John Resig出色博客上的简单JavaScript继承。
And also "Simple JavaScript Inheritance" on John Resig's great blog.
var prototype = new this();
new this()是什么?
实际上意思?
这句话对我来说毫无意义,因为据我了解, this
指向对象而不是构造函数功能。我还尝试过在Firebug中测试语句以弄清楚这一点,而我收到的只是语法错误。
This statement makes no sense to me because my understand has been that this
points to an object and not a constructor function. I've also tried testing statements in Firebug to figure this one out and all I receive is syntax errors.
我的头已经完全旋转了。
My head has gone off into a complete spin.
有人可以详细解释一下吗?
Could someone please explain this in detail?
推荐答案
AJS.Class
有效地*翻译为:
var Person = new AJS.Class({
init: function(name) {
this.name = name;
Person.count++;
},
getName: function() {
return this.name;
}
});
Person.count = 0;
为此:
var Person = function (name) {
this.name = name;
Person.count++;
};
Person.prototype = {
getName: function() {
return this.name;
}
};
Person.extend = AJS.Class.prototype.extend;
Person.implement = AJS.Class.prototype.implement;
Person.count = 0;
因此,在这种情况下, this
AJS.Class.prototype.extend
是指 Person
,因为:
Therefore, in this case, this
in AJS.Class.prototype.extend
refers to Person
, because:
Person.extend(...);
// is the same as
Person.extend.call(Person, ...);
// is the same as
AJS.Class.prototype.extend.call(Person, ...);
*在很多情况下,我都不会忽略;重写是为了简化理解问题。
* There are a lot of cases I don't go over; this rewrite is for simplicity in understanding the problem.
这篇关于令人困惑的JavaScript语句:“ var x = new this();”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!