【废话】 面试时被经理问到其中一个问题让我印象很深刻,因为我想了很久没能答上来。题目是 JavaScript是怎样实现继承的? 面向对象是在开发过程中一直使用的,因此,继承也是最基础的一部分,自己开始接触JS到现在差不多两年多了,这个基础我竟然都没过关,看来我的理论功还要加大力度提升啊!!!我重新查了资料,终于深刻理解下来了。废话就这么多了,Coding Action... 【正文】 大家都知道,C#中使用的是传统的类继承是很简单,但在JS中,可就没这么简单了,因为它使用的是原型(prototype )继承,实现起来相对复杂了一点。 代码如下: //定义 People 对象 var People = function () { }; People.prototype = { Height: 175, Walk: function () { alert("People are walking..."); } } //定义 Me 对象 var Me = function () { }; //设置 Me 的 prototype 属性为 People 对象 Me.prototype = new People(); //将创建 Me 对象的引用指回给 Me Me.prototype.constructor = Me; //修改 Height 属性 Me.prototype.SetHeight = function (v) { Me.prototype.Height = v; } //新增 Stop 动作 Me.prototype.Stop = function () { alert("I'm Stop."); } var m = new Me(); //结果为 People are 175cm tall. alert("People are " + m.Height + "cm tall."); m.SetHeight(185); //结果为 I'm 185cm tall. alert("I'm " + m.Height + "cm tall."); //结果为 People are walking... m.Walk(); //结果为 I'm Stop. m.Stop(); var y = new Me(); //结果为 You're 185cm tall. alert("You're " + y.Height + "cm tall.");