原型链实例及图示
/*测试*/
//构造函数
function Foo(name,age){
this.name = name;
}
//创建实例
Foo.prototype.alertName = function(){
alert(this.name);
}
var f = new Foo('zhan');
f.printName = function(){
console.log(this.name);
}
//测试
f.printName();//zhan
f.alertName();//alert弹出zhan
f.toString();//在隐式原型中没有找到,要去f.__proto__.__proto__中查找
- 原型链图示
instanceof
f instanceof Foo的判断逻辑是:
f 的 proto一层一层往上,能否对应到 Foo.prototype(对应上图)
题目
1 . 如何准确判断一个变量是++数组类型++
var a = [];
var b = 2;
console.log(a instanceof Array); //true
instanceof(b instanceof Array);
//false
2 . 写一个原型链继承的例子
function People(){
this.name = function(){
console.log('people name');
}
}
function Student(){
this.id = function(){
console.log('student id');
}
}
Student.prototype = new People();
//这时候Student这个函数就有了name的属性
var we = new Student();
console.log(we.name,we.id);
3 . 描述new一个对象的过程
function Foo(){
this.a = 1;
this.b = 2;
this.c = 3;
//return this;
}
var fn = new Foo();
console.log(fn); //Foo {a: 1, b: 2, c: 3}
new一个对象的过程分为4步:
var fn ={}; //1.创建一个空对象fn
fn.__ proto __ = Foo.prototype; //2.创建一个指向(原型)text.prototype的指针
Foo.call(fn); //3.将构造函数的作用域赋给新对象,因此Foo函数中的this指向新对象fn,然后再调用Foo函数。于是我们就给obj对象赋值了三个属性;
return fn; //4.返回新对象obj。
4 . zepoto(或其他框架)源码中如何使用原型链
//封装一个Dom查询的例子
function Elem(id){
this.elem = document.getElementById(id);
}
Elem.prototype.html = function(val){
var elem = this.elem;
if(val){
elem.innerHTML = val;
return this;//链式操作
}else{
return elem.innerHTML;
}
}
Elem.prototype.on = function(type,fn){
var elem = this.elem;
elem.addEventListener(type,fn);
}
var div1 = new Elem('div1');
div1.html('<p>hello</p>').on('click',function(){
alert(clicked);
}).html('<p>javascript</p>');