当前位置:学会吧培训频道电脑知识学习网页制作Javascript教程JavaScript中类的定义、继承» 正文

JavaScript中类的定义、继承

[08-08 00:41:27]   来源:http://www.xuehuiba.com  Javascript教程   阅读:8805
概要:一.类的定义: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!&
JavaScript中类的定义、继承,标签:javascript视频教程,javascript教程下载,http://www.xuehuiba.com

一.类的定义:
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.其中类方法、类属性的继承实现的比较牵强,期待更好的方法。


Tag:Javascript教程javascript视频教程,javascript教程下载电脑知识学习 - 网页制作 - Javascript教程
Copyright 学会吧 All Right Reserved.
在线学习社区!--学会吧
1 2 3 4 5 6 7 7 8 9 10 11 12 13