__JavaScript中的原型和继承
我已经研究JavaScript继承好几天了,虽然我已经取得了很大的进步,但有些事情我还不太了解 例如,我发现这种行为相当令人困惑:__JavaScript中的原型和继承,javascript,inheritance,prototype,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&qu
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"
m
的\uuuu proto\uuu
属性指向的对象不是管理器的当前原型。
这有点违反直觉,因为:
即使在创建对象后将属性添加到其原型中,对象也会继承属性
取自
这种行为不能也适用于上述情况吗
有人能澄清一下吗?这有点令人困惑,因为函数本身就是对象:
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 */