构造函数
摘要:
- 构造函数首字母大写(区分够着函数与普通函数)
- 使用new关键词常见构造函数对象(与系统标准对象使用方法一致)
- js的所有对象都有一个proto属性,调用方法obj.__ proto__
- 只有函数有prototype属性,该属性是一个指针,指向一个对象,即对象原型(constructor)
以下为代码演示:
// function Student(name){
// this.name=name;
// this.hello=function(){
// alert("hello"+this.name);
// }
// } 这种构造函数的写法会为每个obj对象创建一个hello()函数,增大内存负担
function Student(props){
this.name=props.name;
this.grade=props.grade;
}
Student.prototype.hello=function(){
alert("hello,"+this.name);
} //这样写把hello()加在了prototype上,每次调用的都是原型上的hello()方法
function createStudent(props){
return new Student(props || {})
} //封装的new函数:1、可以省去new定义,2、参数可以为空,这样多参数可以设置默认值,只传入我们需要的参数即可
//如果创建的对象有很多属性,我们只需要传递需要的某些属性,剩下的属性可以用默认值
构造函数的原型链继承
摘要:JavaScript的原型继承实现方式
- 定义构造函数
- 内部调用call()调用继承的构造函数,并绑定this
- 借助中间函数F,实现原型链的继承,封装inherits()函数
- 继续在新的构造函数上定义新的方法
以下为代码演示:
function Student(props){
this.name=props.name || 'Unnamed';
}
Student.prototype.hello=function(){
alert("hello,"+this.name)
}
function PrimaryStudent(props) {
Student.call(this, props);
this.grade = props.grade || 1;
}
function inherits(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
// 实现原型继承链:
inherits(PrimaryStudent, Student);
// 绑定其他方法到PrimaryStudent原型:
PrimaryStudent.prototype.getGrade = function () {
return this.grade;
};
es-6新增class继承
直接上代码....
class Student{
constructor(name){
this.name=name;
}
hello(){
alert("hello,"+this.name)
}
} //es6--class定义实现原型链的继承,与我们之前是一样的逻辑,只是封装了一下,写法不一样了
class PrimaryStudent extends Student{
constructor(name,grade){
super(name); //用super调用父类的构造方法
this.grade=grade;
}
myGrade(){
alert("我的成绩:"+this.grade)
}
}
var xiaoming=new Student("小明",90);
var zhangsan=new PrimaryStudent("张三",80);
var lisi=new PrimaryStudent("李四",99);
xiaoming.hello();
// xiaoming.myGrade(); 报错
zhangsan.myGrade();
console.log(zhangsan.myGrade===lisi.myGrade);
以上为自己学习总结,欢迎纠错。