Javascript ES5里实现类

本文深入探讨了JavaScript中的类和继承机制,从简单的function实现类到构造函数、原型链的概念,再到类方法、继承方式的多样性。通过实例展示了原型链继承、对象冒充继承以及如何解决继承中传参的问题。同时,文章还提到了静态方法和类的继承问题,以及不同继承方式的优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//1.function 实现类(最简单的类)

 

function Person(){

 

    this.name = "张三";

    this.age = 12;

 

}

 

var p1 = new Person();

console.log(p1.name);

 

//2.构造函数和原型链

function Person1(){

 

    this.name = "张三";

    this.age = 12;

 

    this.run=function(){

 

        console.log(this.name + " is running");

    };

 

}

 

var p1 = new Person1();

p1.run();

 

//原型链上的属性和方法会被多个实例共享,构造函数不会

Person1.prototype.sex = "man";      //原型链上定义属性

Person1.prototype.work = function(){//原型链上定义方法

 

    console.log(this.name + "is working");

 

}

 

var p2 = new Person1();

console.log(p2.sex);

p2.work();

console.log(p1.sex);

p1.work();


 

//3.类里的静态方法,即 类方法

Person1.getInfo=function(){

 

    console.log("静态方法,类方法");

}

 

//4.类中的继承,原型链 和对象冒充

function Person2(){

 

    this.name = "张三";

    this.age = 12;

 

    this.run=function(){

 

        console.log(this.name + " is running");

    };

 

}

//对象冒充继承,可以继承构造函数 里的属性和方法,不能继承 原型链上的属性和方法

function Student(){

 

    Person1.call(this);

 

}

 

var student1 = new Student();

student1.run();

 

//原型链上的继承和方法不能继承

//student1.work();  

console.log(student1.sex);

 

//5. 原型链继承,子类即可以继承构造函数属性,也可以继承原型链上的属性和方法

function Student1(){

 

}

Student1.prototype = new Person1();

 

console.log("--------原型链继承-----------");

var student2 = new Student1();

student2.run();

student2.work();  

console.log(student2.sex);

 

//6.原型链上继承的问题,不能给父类传参数

function Animal(name,age){

 

    this.name = name;

    this.age = age;

 

    this.say=function(){

        console.log(this.name + " 在叫~");

    }

}

 

function Cat(name,age){

 

}

 

Cat.prototype = new Animal();

 

var cat1 = new Cat("苗苗",2);

cat1.say();// Cat里的实际参数不能传给Animal

 

//7.结合冒充继承(构造函数)和原型链继承来实现传参

 

function Dog(name,age){

 

    Animal.call(this,name,age);

}

 

//构造函数继承 都可以实现传参

Dog.prototype = new Animal();

//原型链继承

//Dog.prototype = Animal.prototype;

 

console.log("------构造函数结合原型链继承--------")

var dog1 = new Dog("旺财",3);

dog1.say();



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值