asy*_*ric 6 javascript inheritance prototype
我已经研究了几天的javascript继承,尽管我已经取得了很大的进步,但还有一些我还不太了解的东西.
例如,我觉得这种行为很混乱:
var Employee = function Employee() { this.company = 'xyz'; };
var Manager = function Manager() { this.wage = 'high'; };
var m = new Manager();
m; // { "wage": "high", __proto__ : Manager } -- no problems so far.
Manager.prototype = new Employee();
var n = new Manager;
m.company; // undefined
n.company; // "xyz"
Run Code Online (Sandbox Code Playgroud)
m的__proto__属性指向的对象是不Manager的当前原型.这有点违反直觉,因为:
即使在创建对象后将对象添加到其原型中,对象也会继承属性.
这种行为也不能适用于上述案例吗?
任何人都可以澄清吗?
小智 4
这有点令人困惑,因为函数本身就是对象:
function Employee() {this.company = 'xyz';}
function Manager() {}
var m = new Manager();
Manager.prototype = new Employee();
/* You set the prototype on the Manager function (object),
your m instance and Manager function are separate objects.
At this point the prototype of m is still undefined */
m = new Manager();
m.company; // 'xyz'
/* Creating a new Manager copies the new prototype */
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
319 次 |
| 最近记录: |