Tri*_*iad 6 javascript prototype-chain angularjs
我正在阅读Javascript原型属性如何与继承一起工作,然后开始查看Angular.js代码并提出了一些问题.
首先,我读到prototype属性指向一个具有"constructor"属性的对象,该属性指向用于创建对象的原始函数.例如:
// This is the constructor
function Shape() {
this.position = 1;
}
// The constructor points back to the original function we defined
Shape.protoype.constructor == Shape;
Run Code Online (Sandbox Code Playgroud)
原型还包含由我们或Javascript语言本身定义的任何其他方法或属性,并且这些方法或属性由对象的所有实例共享.如果你想让一个名为Square的对象继承自Shape,你需要设置Square的原型等于Shape的一个新实例,因为Square.prototype的内部[[prototype]]属性被设置为Shape.prototype属性的公共对象值. .
function Square() {}
Square.prototype = new Shape();
var square = new Square();
square.position; // This will output 1
Run Code Online (Sandbox Code Playgroud)
这一切都对我有意义.
但是,我有一个问题的Angular.js代码似乎与所有这些相关,但做了一件我不理解的事情.它似乎没有处理继承,所以我可以理解为什么会有差异,但我只是好奇为什么他们按照他们的方式编写它.
在Angular.js中,有一个HashMap对象和一个Lexer对象,但它们的定义不同,但似乎是以相同的方式实例化和使用.首先定义Lexer构造函数,然后将原型设置为包含应由Lexer的所有实例共享的方法的对象文字.这一切都有道理.我不明白的是为什么他们指定"构造函数"属性并将其设置为"Lexer",而不是下面的HashMap.
var Lexer = function(options) {
this.options = options;
};
// Notice they specify Lexer as the constructor even though they don't for HashMap below
Lexer.prototype = {
constructor: Lexer,
lex: function(text) { ... },
is: function(ch, chars) { ... },
peek: function(i) { ... },
isNumber: function(ch) { ... },
isWhitespace: function(ch) { ... },
isIdent: function(ch) { ... },
isExpOperator: function(ch) { ... },
throwError: function(error, start, end) { ... },
readNumber: function() { ... },
readIdent: function() { ... },
readString: function(quote) { ... }
};
Run Code Online (Sandbox Code Playgroud)
然后,如果你查看HashMap代码,他们会做同样的事情,除了他们没有指定构造函数属性.为什么是这样?它似乎工作完全相同,我已经测试过构造函数仍然被调用.
// The HashMap Constructor
function HashMap(array, isolatedUid) {
if (isolatedUid) {
var uid = 0;
this.nextUid = function() {
return ++uid;
};
}
forEach(array, this.put, this);
}
HashMap.prototype = {
put: function(key, value) { ... },
get: function(key) { ... },
remove: function(key) { ... }
};
Run Code Online (Sandbox Code Playgroud)
当没有继承时,构造函数属性是可选的,所以也许有一个人编写了Lexer而另一个人编写了HashMap,并且决定指定构造函数?
默认情况下,每个原型都有一个constructor属性,该属性引用它"所属"的功能.
function A() {
}
console.log(A.prototype.constructor === A); // trueRun Code Online (Sandbox Code Playgroud)
如果使用对象文字或其他一些构造的原型覆盖整个原型,则该constructor值将被删除并保持未定义或具有其他值.
function A() {
}
A.prototype = {
greeting: "Hello!"
};
console.log(A.prototype.constructor === A); // falseRun Code Online (Sandbox Code Playgroud)
constructor为了使构造函数正确运行,不需要prototype 属性,但人们通常会重新分配prototype.constructor回其初始值以保持一致性,这就是您所看到的Lexer.
考虑:
function A() {
}
function B() {
}
B.prototype = Object.create(A.prototype);
var b = new B();
console.log(b.constructor === A); // true
console.log(b.constructor === B); // false
B.prototype.constructor = B;
console.log(b.constructor === A); // false
console.log(b.constructor === B); // trueRun Code Online (Sandbox Code Playgroud)
人们只能推测为什么这被遗漏了HashMap.我怀疑这是出于任何好的理由,可能只是一个疏忽.
| 归档时间: |
|
| 查看次数: |
221 次 |
| 最近记录: |