日期:2014-05-16 浏览次数:20425 次
function Parent() { var parentPrivate = "parent private data"; var that = this; this.parentMethodForPrivate = function () { return parentPrivate; }; console.log("parent"); } Parent.prototype = { parentData: "parent data", parentMethod: function (arg) { return "parent method"; }, overrideMethod: function (arg) { return arg + " overriden parent method"; } } function Child() { // super constructor is not called, we have to invoke it Parent.call(this); console.log(this.parentData); var that = this; this.parentPrivate = function () { return that.parentMethodForPrivate(); }; console.log("child"); } //inheritance Child.prototype = new Parent(); // parent Child.prototype.constructor = Child; //lets add extented functions Child.prototype.extensionMethod = function () { return " child’ s" + this.parentData; }; //override inherited functions Child.prototype.overrideMethod = function () { //parent’s method is called return" Invoking from child " + Parent.prototype.overrideMethod.call(this, "test"); }; var child = new Child(); // parent // parent data // child console.log(child.extensionMethod()); //child’s parent data console.log(child.parentData); //parent data console.log(child.parentMethod()); //parent method console.log(child.overrideMethod()); //Invoking from child test overriden parent method console.log(child.parentPrivate()); // parent private data console.log(child instanceof Parent); //true console.log(child instanceof Child); //true