深入理解javascript 对象原型和构造函数
对象的创建过程
当你使用new操作符调用F构造函数时,会经历以下步骤:
1.创建一个空对象,作为将要返回的实例对象
2.将空对象的原型指向构造函数的prototype属性,也就是F构造函数的prototype属性。
3.将空对象赋值给构造函数内部的this关键字,也就是this关键字会指向实例对象。
4.开始执行构造函数内部的代码。
var student =function (age) {
this.age =age;
};
var s = new student(15);
console.log(s.__proto__===student.prototype); //=>true
类是继承
简单的继承:
注:为什么使用student.prototype.constructor =student
解:如图
s实例构造函数引用指向了person 实例化student 其应该对其显示的修改使其指向student函数
var person = function (name,book) {
this.name = name;
this.book =book;
};
var student =function (age,name,book) {
this.age =age;
person.call(this,name,book); //改变this指向
};
person.prototype.height = 175;
student.prototype = new person();
student.prototype.constructor =student; //使s 的constructor 引用 student
var s = new student(18,'zl','js');
console.log(s.constructor) ;
console.log(student.prototype.constructor)
console.log(s.name,s.age,s.book);
对其进行封装
/*
*
* 类式继承
*
* */
function extend(subClass,superClass) {
var f = function () {};
f.prototype =superClass.prototype;
subClass.prototype = new f();
subClass.prototype.constructor = subClass;
subClass.superclass =superClass.prototype;
if(superClass.prototype.constructor==Object.prototype.constructor){
superClass.prototype.constructor =superClass;
}
}
function person(name,age) {
this.name = name;
this.age =age ;
}
function student(books,name,age) {
student.superclass.constructor.call(this,name,age)
this.books = books;
this.getName = function () {
console.log(this.books);
}
};
extend(student,person);
//测试
var s = new student('js','zs',9);
s.getName();
console.log(s.name,s.age);
原型式继承
/*
* 原型式继承:不需要使用类来定义对象的结构,只需要直接创建一个对象,
* 这个对象可以被新的对象重用(利用的是原型链查找的工作机制)
*
*
* 使用clone函数
* */
function clone(obj) {
function fun() {};
fun.prototype = obj;
return new fun;
};
var person = function (name) {
this.name= name;
this.age = 18;
}
var student = clone(new person('zs'));
student.name = 'zl';
student.age = 15;
console.log(student.age,student.name);
var student1 = clone(new person('zs'));
console.log(student1.age,student1.name);
//因为传递的是一个对象,可以使用下面的方法
var people = {
name:'zs',
age:18
};
var s = clone(people);
console.log(s);
s.name='zl';
s.age=15;
console.log(s.name,s.age);
var s1 = clone(people);
console.log(s1.name,s1.age);
s.__proto__.age=15;
s.__proto__.name='zl';
console.log(s1.name,s1.age);
图解: