打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
javascript中类的定义和继承的用法
javascript中类的定义和继承方法不一,下面介绍常用方法:
一.类的定义:
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.其中类方法、类属性的继承实现的比较牵强,期待更好的方法。
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
传智播客:javascript中模拟继承和接口 - habernate的日志 - 网易博客
javascript的prototype
JavaScript语言知识收藏
【web】面向对象的javascript - 应用,一定要应用 - BlogJava
Javascript面向对象编程:继承
构造函数的继承
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服