JavaScript中类的定义、继承

王朝学院·作者佚名  2009-06-24
窄屏简体版  字體: |||超大  

一.类的定义:

1.混合的构造函数/原型:

程序代码

function Parent(name) {

//实例属性

this.name = name;

}

//实例方法

Parent.prototype.hello = function () {

alert("parent!");

}

//类属性

Parent.PI = 3.14159;

//类方法

Parent.say = function () {

alert("say");

}

2.动态原型:

程序代码

function Parent(name) {

//实例属性

this.name = name;

if (typeof Parent._initialized == "undefined") {

//实例方法

Parent.prototype.hello = function () {

alert("parent!");

};

//类属性http://qqface.knowsky.com/

Parent.PI = 3.14159;

//类方法

Parent.say = function () {

alert("say");

}

Parent._initialized = true;

}

}

其中方法1更常用。

2.类的继承:

程序代码

function Child(name, age) {

Parent.call(this, name);

this.age = age;

}

Child.prototype = new Parent();

//Child.prototype = Parent.prototype;

Child.prototype.hello = function () {

alert("child!");

}

for (var classMember in Parent) {

Child[classMember] = Parent[classMember];

}

注意:

1.不能用Child.prototype = Parent.prototype,否则会导致:修改Child的方法同时也修改Parent的方法。

2.使用Child.prototype = Parent.prototype也可以使Child的实例child instanceof Parent为true。

3.其中类方法、类属性的继承实现的比较牵强,期待更好的方法。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航