JS面向对象

2019-04-25  本文已影响0人  Mr_J316

2019-04-25

构造函数

Javascript提供了构造函数(Constructor)模式实现类的设计与封装。

function 构造函数名(参数1,参数2 … ){
    this.属性1 = 参数1;
    this.属性2 = 参数2;
    …..
    this.方法1  = function(参数1,参数2…){
    }
    ……
}

var 引用名 = new 构造函数名(参数1,参数2…);

class关键字

​ ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。类的数据类型本质就是函数。

class 类名{
    constructor(参数1,参数2… ) {
        this.属性1 = 参数1;
        this.属性2 = 参数2;
        ……
    }
    方法1(参数1,参数2…){
    }
    … ….
} 
var 引用名 = new 类名(参数1,参数2…);

继承

原型链继承

​ 每个JavaScript构造函数都有一个prototype属性,可以指向另一个对象。当访问对象某个属性时,JavaScript引擎会在该对象的所有属性中查找,如果没有找到就从prototype属性指向的对象中查找。

function Animal() {
    this.eat = function() {
        document.write("吃东西" + "<br />");
    }
}
function Bird() {
    this.fly = function() {
        document.write("飞行" + "<br />");
    }
}
Bird.prototype = new Animal();

var obj = new Bird();
obj.fly();
obj.eat();

使用call方法继承

function Account(id, password, balance) {
    this.id = id;
    this.password = password;
    this.balance = balance;
}
function CreditAccount(id, password, balance, overdraft) {
    Account.call(this, id, password, balance);
    this.overdraft = overdraft;
}

var acc = new CreditAccount("0001", "123456", 1000, 20000);
document.write("账号:" + acc.id + "<br />");
document.write("密码:" + acc.password + "<br />");
document.write("余额:" + acc.balance + "<br />");
document.write("透支额:" + acc.overdraft + "<br />");

通过实例直接继承

function Account(id, password, balance) {
    this.id = id;
    this.password = password;
    this.balance = balance;
}

var acc1 = new Account("0001", "123456", 1000);
var acc2 = Object.create(acc1);
acc2.overdraft = 20000;
document.write("账号:" + acc2.id + "<br />");
document.write("密码:" + acc2.password + "<br />");
document.write("余额:" + acc2.balance + "<br />");
document.write("透支额:" + acc2.overdraft + "<br />");

通过extends关键字继承

class 子类名 extends 父类名{
}
class CreditAccount extends Account{
    
    constructor(id, password, balance,overdraft) {
        super(id, password, balance);
        this.overdraft = overdraft;
    }
    
    show () {
       return super.show()+",透支额:"+this.overdraft;
    }
}

var acc1 = new CreditAccount ("0001", "123456", 1000, 5000);
document.write(acc1.show());

闭包

​ 变量的作用域有两种:全局变量和局部变量。JS在函数内部可以直接读取全局变量。在函数外部则无法读取函数内的局部变量。

// 既然f2可以读取f1中的局部变量,那么只要把f2作为返回值,就可以在f1外部读取它的内部变量了
// f2函数即为闭包。
function f1(){
  var n=999;
  function f2(){
    alert(n); 
  }
  return f2;
}
var result = f1();
result();

​ 由于在Javascript语言中,只有函数内部的子函数才能读取函数的局部变量,因此可以把闭包简单理解成"定义在函数内部的函数"。

闭包的用处:

读取函数内部变量

将函数变量的值始终保持在内存中,延长生存期

上一篇 下一篇

猜你喜欢

热点阅读