日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

js 繼承(一)

 宜賓翠屏區(qū) 2019-04-07

// 定義一個(gè)動(dòng)物類
  function Animal (name) {
  // 屬性
  this.name1 = name||'Animal';
  // 實(shí)例方法
  this.sleep = function(){   document.write(this.name + '正在睡覺!');  }
}
// 原型方法
Animal.prototype.eat = function(food) {   document.write(this.name + '正在吃:' + food);  };
function Cat(){   }
Cat.prototype = new Animal("333333");  //父函數(shù)作為實(shí)例,成為子函數(shù)的一個(gè)屬性 將父類的實(shí)例作為子類的原型
Cat.prototype.name = 'cat'; 
var cat = new Cat();
alert(cat.name)
alert(cat.name1) 
    cat.eat('fish');
cat.sleep();
alert(cat instanceof Animal)
alert(cat instanceof Cat)
===========================================

借用構(gòu)造函數(shù)
使用call和apply借用其他構(gòu)造函數(shù)的成員, 可以解決給父構(gòu)造函數(shù)傳遞參數(shù)的問題, 但是獲取不到父構(gòu)造函數(shù)原型上的成員.也不存在共享問題

// 創(chuàng)建父構(gòu)造函數(shù)
function Person(name){
  this.name = name;
  this.freinds = ['小王', '小強(qiáng)'];
  this.showName = function(){
     console.log(this.name);
  }
}
// 創(chuàng)建子構(gòu)造函數(shù)
 function Student(name){
  // 使用call借用Person的構(gòu)造函數(shù)
  Person.call(this, name);
 }
 // 測試是否有了 Person 的成員
 var stu = new Student('Li');
 stu.showName(); // Li
 console.log(stu.friends); // ['小王','小強(qiáng)']
===================================================

(5) 組合繼承  (借用構(gòu)造函數(shù) + 原型式繼承)

// 創(chuàng)建父構(gòu)造函數(shù)
function Person(name,age){
    this.name = name;
    this.age = age;
    this.showName = function(){
        console.log(this.name);    }
                      }
// 設(shè)置父構(gòu)造函數(shù)的原型對象
Person.prototype.showAge = function(){ console.log(this.age); }
// 創(chuàng)建子構(gòu)造函數(shù)
function Student(name){
    Person.call(this,name);
                }
// 設(shè)置繼承
Student.prototype = Person.prototype;
Student.prototype.constructor = Student;
=================================================

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多