js中我们可以定义如下对象
'use strict'
var Student = {
name: 'Robot',
height: 1.2,
run: function () {
console.log(this.name + ' is running...');
}
};
var xiaoming = {
name: '小明'
};
将xiaoming指向student
//xiaoming的原型指向了对象student 小明从student类继承过来
xiaoming.__proto__ = Student;
xiaoming对象中有name属性,但是没有run方法,可以调用对应的Student类的run方法
console.log(xiaoming.name);
xiaoming.run();
js的原型链和java的class的区别就在,他没有class的概念,所有的对象都是实例,所谓继承关系只不过是把一个对象的原型指向另一个对象而已,
var Bird = {
fly:function() {
console.log(this.name + "is flying");
}
}
xiaoming.__proto__ = Bird;
xiaoming.fly();
这时候小明便成了一个鸟
不要直接用obj.__proto__
去改变一个对象的原型,
可以使用构造函数 将name传入即可。
var Student = {
name:'Robot',
height:1.2,
run:function() {
console.log(this.name + " is runing");
}
}
function createStudent(name){
var s = Object.create(Student);
s.name = name;
return s;
}
var xiaoming = createStudent('小明');
xiaoming.run();
js对每个创建的对象都会设置一个原型,指向他的原型对象.
当使用obj.xxx时,访问一个对象的属性时,现在当前对象上查找该属性,如果没有找到,再去原型对象上找,如果一直没有找到,就一直上溯到object.prototype对象上找,最后,如果还是没有找到,则只能返回undefined.
例如 array的原型对象便是
arr -> arr.prototype --> object.prototype -> null
实际上,函数也是一个对象,原型链是
foo -> function.prototype -> object.prototype -> null
可以用类来进行继承
class Student{
constructor(name){
this.name = name;
}
hello() {
alert("hello" + this.name);
}
}
var xiaoming = new Student("小明");
xiaoming.hello();
在es6中。
class primaryStudent extends Student{
constructor(name,grade){
super(name); //父类的构造方法.
this.grade = grade;
}
myGrade(){
alert("i am a student");
}
}
var pri = new primaryStudent("曹凯强",100);
pri.hello();
pri.myGrade();
可以调用父类的hello方法 或者自己子类的myGrade()方法。表示原型链对象来自Student
class转化为prototype的工具 babel
原型链的继承参考廖雪峰的原型继承
function Student(props){
this.name = props.name || 'Unnamed';
}
Student.prototype.hello = function() {
alert("hello" + this.name);
}
//primaryStudent的构造函数
function PrimaryStudent(props){
Student.call(this,props);
this.grade = props.grade || 1;
}
//空函数
function F(){
}
//把F的原型指向student.prototype
F.prototype = Student.prototype;
//把primaryStudent指向一个新的F对象,F对象的原型正好指向student
PrimaryStudent.prototype = new F();
// 把PrimaryStudent原型的构造函数修复为PrimaryStudent:
PrimaryStudent.prototype.constructor = PrimaryStudent;
PrimaryStudent.prototype.getGrade = function() {
return this.grade;
}// 创建xiaoming:
var xiaoming = new PrimaryStudent({
name: '小明',
grade: 2
});
xiaoming.name; // '小明'
xiaoming.grade; // 2
console.log(
// 验证原型:
xiaoming.__proto__ === PrimaryStudent.prototype); // true
console.log(xiaoming.__proto__.__proto__ === Student.prototype); // true)
原型链的相关知识:
http://www.cnblogs.com/shuiyi/p/5305435.html
https://www.cnblogs.com/libin-1/p/5820550.html
这个__proto__指向的就是他的构造函数的prototype 而这个函数a的prototype对象的构造函数是谁呢? 没错就是开头说到的Object.prototype。
当我们声明一个函数B时就自动创建了prototype对象。而b是构造函数的B的实例,这是候b是一个对象,而我们知道,对象只有__proto__属性。而这个属性是指向他的构造函数(B)的prototype属性。这时候我们来打印一下b
function B(b){
this.b = b;
}
var b = new B('lc');
console.log(b);