关于Javascript继承,我可以'我不明白
There is something about Javascript inheritance that I can't understand
我正在阅读Mozilla开发者网络的面向对象JavaScript简介,在开始使用node.js之前,是时候学习如此严肃的JavaScript了。
无论如何,继承的事情对我来说似乎很模糊。从文档中复制和粘贴:
// define the Person Class
function Person() {}
Person.prototype.walk = function(){
alert ('I am walking!');
};
Person.prototype.sayHello = function(){
alert ('hello');
};
这很容易,但Student
继承会使事情变得复杂。其他人认为以下三种说法本质上是一样的吗?
// define the Student class
function Student() {
// Call the parent constructor
Person.call(this);
}
// inherit Person
Student.prototype = new Person();
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
我理解第一个(调用父构造函数),因为它与Java、PHP等非常相似。
为什么需要调用Student.prototype
和?Student.prototype.constructor
需要一个明确的解释。为什么这个代码:
// define the Student class
function Student() {
// Call the parent constructor
Person.call(this);
}
var student1 = new Student();
继承还不够用吗?
EDIT:关于构造函数的事情,这里已经回答了。
这不起作用:
function Student() {
Person.call(this);
}
var student1 = new Student();
因为CCD_ 4的原型属性在CCD_ 5实例上不可用。Person.call(this)
仅调用具有特定this
值的Person
(即Student
实例)。但是Person
函数是完全空的,所以在这里它什么都不做。CCD_ 11和CCD_ 12之间除了无用的CCD_。
为了得到Person
的函数,.prototype
赋值是必要的。
之前:
<a Student instance>
its prototype: Student.prototype, with all student functions
its prototype: Object.prototype
之后:
<a Student instance>
its prototype: <a Person instance>, with all student functions if you add them
its prototype: Person.prototype, with all person functions
its prototype: Object.prototype
如果您使用Node.js,我建议您研究ECMAScript 5的对象创建方法。MDN在这里有一个页面,这可能是一个很好的指南。另请参阅John Resig对新方法的概述。当你使用Java这样的经典OO语言时,很难理解原型继承。祝你好运
相关文章:
- Javascript模块系统I'I’我正在努力,但搞不明白
- 关于Javascript继承,我可以'我不明白
- 我可以'我不明白为什么我能;不要在JavaScript中更改蜡笔的颜色
- 意外;在我的JavaScript中,我不明白为什么
- 我没有'我不明白“;temp<<=y"在这个javascript程序中执行
- 我不明白JavaScript中的这种比较是如何工作的
- 我不明白的jQuery或javascript语法
- 我不明白 javascript 中的 setTimeout(fn,0) 是如何工作的
- 我不明白我的Javascript代码出了什么问题
- Don'我不明白为什么这个JavaScript函数可以用一种方法调用,而不能用另一种方法
- Javascript方法崩溃了——我只是不明白为什么
- 有人能让我明白什么是“;这个“;关键字及其在JavaScript中的使用
- Javascript-将零引到一个数字,将数字转换为不同的数字.不明白为什么会发生这种事
- javascript闭包的最后一部分我仍然没有'我不明白
- Code Academy JavaScript数组-我可以'我不明白为什么这个代码不正确(新手)
- 不明白这个checkingempty -form-value-code是如何工作的(javascript)
- 我不明白为什么这个javascript不能工作
- Javascript中的新手-使用JSfiddle,缺少分号,但我没有'我不完全明白在哪里
- Javascript/JQuery 事件参数.我不明白这个“e”论点是什么或做什么
- 我不明白,存在于另一个对象中的Javascript对象有自己的活动