原型继承
function Person(name,age){
this.grandpa = 'Person';
}
Person.prototype.say = function (){
console.log(this.name,this.age)
}
function Student(name,age,subject,score){
this.name=name;
this.age=age;
this.subject=subject;
this.score=score;
}
Student.prototype = new Person;
Student.prototype.showScore = function(){
console.log(this.subject+":"+this.score)
}
var stu = new Student('ym',18,'Math',100);
stu.showScore();
stu.say();
console.log(stu.grandpa)
构造函数继承?
感觉不是严格意义的继承, 顶多算代码复用
// js 继承:
// call apply
//call --》 obj.call(方法,var1,var2,var3....)
//apply--> obj.apply(方法,[var1,var2,var3]);
function person(name,age,len){
this.name = name;
this.age = age;
this.len = len;
this.say = function(){
alert(this.name+":"+this.age+":"+this.len);
}
}
//call继承
function student(name,age){
person.call(this,name,age);
}
//apply继承
function teacher(name,age,len){
person.apply(this,[name,age,len])
}
var per = new person("张三",25,"170");
per.say();
var stu = new student("李四",18);
stu.say(); // 李四 18 undefined
var tea = new teacher("王武",20,"180");
tea.say();
函数对象
* 每个函数在定义时会自动添加一个prototype属性, 它默认指向一个Object空对象(即称为: 原型对象)
* 原型对象中有一个属性constructor, 它指向函数对象
* 作用: 函数的所有实例对象自动拥有原型中的属性(方法)
实例对象
* 创建对象时自动添加__proto__属性, 默认值为构造函数的prototype属性值
Function
* Function是通过new自己产生的实例
原型prototype
* 创建的每一个函数,解析器都会向函数中添加一个属性prototype 对应着一个对象,如果函数作为普通函数调用prototype没有任何作用
* 当new 构造函数时,实例对象中都会有一个隐式原型属性__proto__,指向构造函数的prototype
* 访问对象的一个属性或方法时,它会先在对象自身中寻找,有则直接使用,没有则会去原型对象中寻找
* 原型对象相当于公共区域,相同构造函数的实例都可以访问这个原型对象
* 创建构造函数时,可以将这些对象共有的属性和方法,统一添加到构造函数的原型对象中,
* 这样不用分别为每一个对象添加,造成重复声明 , 也不会影响到全局作用域,就可以使每个对象都具有这些属性和方法了

image
网友评论