前言
正文
一 构造函数
//构造函数 function MathHandle(x,y){
this.x=x; this.y=y; } MathHandle.prototype.add=function(){
return this.x+this.y; } var m=new MathHandle(1,2); console.log(m.add())
二 JavaScript中class的基本语法
class MathHandle{
constructor(x,y){
this.x=x; this.y=y; } add(){
return this.x+this.y; } } const m=new MathHandle(3,2); console.log(m.add())
三 运行比较
console.log(typeof MathHandle) //'function' console.log(MathHandle.prototype.constructor===MathHandle) //true //函数都是有显示原型的,prototype就是显示原型,prototype默认有一个constructor属性,这个属性等于MathHandle本身 console.log(m.__proto__===MathHandle.prototype) //true //m是构造函数new出来的一个实例,所有的实例都有一个隐式原型__proto__等于MathHandle的显示原型
结论:class就是语法糖,在语法上更贴近面向对象的写法
四 Class继承的写法
class Animal{
constructor(name){
this.name=name } eat(){
alert(this.name+'eat') } } class Bird extends Animal{
constructor(name){
super(name)//注意!!!!! this.name=name; } say(){
alert(this.name + 'say') } } const bird=new Bird('Pengguin') bird.say() bird.eat()
五 继承JS的写法
//动物 function Animal(){
this.eat=function(){
alert('eat') } } //鸟 function Bird(){
this.bark=function(){
alert('bark') } } //绑定原型,实现继承 Bird.prototype=new Animal() //企鹅 var Pengguin=new Bird() Pengguin .bark() Pengguin.eat()
结论:通过语法糖可增加代码的可读性.
结尾
不积硅步无以至千里,不积小流无以成江河.学习更是这样,点点滴滴的学与总结.
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/176512.html原文链接:https://javaforall.net
