function student(props){ this.name=props.name || '匿名';//默认是匿名 this.grade=props.grade || 1; } student.prototype.hello=function(){ console.log('hello '+this.name); } function createStudent(props){ return new student(props||{}) } var xiaoming=createStudent({ name:'xiaoming' }); xiaoming.hello();//hello xiaoming
传进一个数组
function animal(name,age,grade){ this.name=name; this.age=age; this.grade=grade; } animal.prototype.hello=function(){ console.log('hello '+this.name); } var chicken=new animal('chicken',3,12); chicken.hello();//hello chicken
我理解的构造函数就是用new()实例化去构造
看了原型继承,发现原型继承不了
所以就看代码
function student(name){ this.name=name||'unname'; } student.prototype.hello=function(){ console.log('hello'+this.name) } function cat(grade){ student.call(this,grade); this.grade=grade||12 } var a=new cat()//a.name=unname,a.grade=12,a.hello() is not a function不可以继承student的原型, function f(){} f.prototype=student.prototype; cat.prototype=new f() var b=new cat();//b.name=unname,b.grade=12,b.hello()='hello unname'可以继承student的原型
通过call来调用继承,并绑定this
也可以用class来extends
class student{ constructor(name){ this.name=name } hello(){ console.log('hello'+this.name) } } class cat extends student{ constructor(name,grade){ super(name); this.grade=grade; } myGrade(){ console.log('my grade is'+this.grade) } } var a=new cat() //a.name,a.hello(),a.grade,a.myGrade()都能用