温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在JavaScript中定义继承

发布时间:2021-05-10 17:35:49 来源:亿速云 阅读:145 作者:Leah 栏目:web开发

如何在JavaScript中定义继承?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

JavaScript的特点

1.JavaScript主要用来向HTML页面添加交互行为。 2.JavaScript可以直接嵌入到HTML页面,但写成单独的js文件有利于结构和行为的分离。 3.JavaScript具有跨平台特性,在绝大多数浏览器的支持下,可以在多种平台下运行。

基类定义如下:

// base class
function Animal(t)
{
   if(typeof t==='string')
    this.type=t;
   else
   {
    if(t)
      this.type=t.toString();
    else
      this.type='Animal'
   }
   this.speak=function(str)
   {
    if(str)
      console.log(this.type+' said '+str);
    else
      throw "please specify what you want to say!";
   }
}

1. 原型继承 (javascript 类库本身基于原型继承)

String, Number , Boolean 这三大原始类型 我们可以很直接的通过prototype 检查到他们继承自Object.

Date, RegExp ,Array 这三应该是间接继承了Object, 他们的prototype属性很特殊 :

Date.prototype =Invalid Date
RegExp.prototype=/(?:)/
Array.prototype=[]

原型继承代码如下: (可以看到Mokey 原型链上的Animal和Object)

// Monkey : Animal 
function Monkey(name,age)
{
   this.name=name;
   this.age=age;
}
Monkey.prototype=new Animal('Monkey');
// Example 01
var m=new Monkey('codeMonkey',10);
    /*
    Monkey:
    age: 10
    name: "codeMonkey"
      __proto__: Animal
      speak: function (str)
      type: "Monkey"
        __proto__: Animal
        constructor: function Animal(t)
          __proto__: Object 
*/
console.log(m.type); // Monkey
console.log(m.name); // codeMonkey
console.log(m.age); // 10
m.speak('hello world') // Monkey said hello world

2. 调用父类构造函数 ( 通过传递子类的this指针 , 将原本是父类的公开成员直接添加到了子类中,从子类原型链中无法看出继承关系)

// Human:Animal 
function Human(id,name)
{
    // call base class's constuctor function
   Animal.call(this,'Human');
   this.id=id;
   this.name=name;
}
var h=new Human(1,'leon');
/*
id: 1
name: "leon"
speak: function (str)
type: "Human"
    __proto__: Human
    constructor: function Human(id,name)
      __proto__: Object
*/
h.speak('hello world'); // Human said hello world 
console.log(h.type); // Human

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI