在命名规则上,构造函数通常是首字母大写,普通函数遵守小驼峰式命名法。 在函数调用的时候:javascript
function fn() { }java
构造函数:函数
1. new fn()<br/>
2 .构造函数内部会建立一个新的对象,即f的实例<br/>
3. 函数内部的this指向 新建立的f的实例<br/>
4. 默认的返回值是f的实例<br/>
复制代码
普通函数:ui
1. fn()<br/>
2. 在调用函数的内部不会建立新的对象<br/>
3. 函数内部的this指向调用函数的对象(若是没有对象调用,默认是window)<br/>
4. 返回值由return语句决定
复制代码
构造函数的返回值:this
有一个默认的返回值,新建立的对象(实例);
当手动添加返回值后(return语句):
1. 返回值是基本数据类型-->真正的返回值仍是那个新建立的对象(实例)
2. 返回值是复杂数据类型(对象)-->真正的返回值是这个对象
复制代码
构造函数:spa
function handleMath(x, y) {
this.x = x,
this.y = y
}
handleMath.prototype.add = function(){
return this.x + this.y
}
var m = new handleMath(1, 2);
console.log(m.add());
复制代码
class语法:prototype
class handleMath {
constructor(x, y){
this.x = x;
this.y = y;
}
add(){
return this.x + this.y;
}
}
var m = new handleMath(1, 2);
console.log(m.add());
复制代码
typeof handleMath 是 function
class只是一个语法糖。code
是否是有点感受了?对象
在来看下继承:继承
构造函数实现:
function Animal() {
this.eat = function(){
console.log('dog eat')
}
}
function Dog() {
this.dark = function(){
console.log('dog dark')
}
}
Dog.prototype = new Animal();
var dogNo1 = new Dog();
dogNo1.eat();
dogNo1.dark();
复制代码
class 函数实现
class Animal{
constructor(name){
this.name = name;
}
eat (){
console.log('dog eat')
}
}
class Dog extends Animal{
constructor(name){
super(name);
this.name = name;
}
say() {
console.log(this.name + ' say')
}
}
var dogNo2 = new Dog('lili');
dogNo2.say();
dogNo2.eat();
复制代码
总结: