前言
学习JS中函数的时候,看到了原型链的内容,不理解,查资料,发现了语法糖的定义.
首先说明一下语法糖的定义百度百科上的定义:
语法糖(Syntactic sugar),也译为糖衣语法,是由英国计算机科学家彼得·约翰·兰达(Peter J. Landin)发明的一个术语,指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。
正文
一 构造函数
构造函数比较容易理解的:
如下的构造函数就是求两个数和的函数.看起来比较简单
//构造函数
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()
结论:通过语法糖可增加代码的可读性.
结尾
不积硅步无以至千里,不积小流无以成江河.学习更是这样,点点滴滴的学与总结.