这篇文章主要说原型及原型链, 鉴戒了一些网络大神的想法, 有什么疑问可以提出来大家一起共同解决
1. 原型的五条规则
所有的引用类型都可以自定义添加属性
所有的引用类型都有自己的隐式原型 (proto)
函数都有自己的显式原型 (prototype)
所有的引用类型的隐式原型都指向对应构造函数的显示原型
使用引用类型的某个自定义属性时, 如果没有这个属性, 会去该引用类型的 proto(也就是对应构造函数的 prototype) 中去找
原型链. png
- function Foo(name) {
- this.name = name;
- // return this; // 本身会执行这一步
- }
- Foo.prototype.alertName = function() {
- alert(this.name);
- }
- var f = new Foo('shiyanping');
- f.printName = function() {
- console.log(this.name);
- }
- f.alertName(); // f.__proto__ -> Foo.prototype
- f.printName();
- console.log(f.toString()); // f.__proto__.__proto__
2. 如何准确判断一个变量是数组类型
arr instanceof Array
instanceof 判断一个引用类型是什么引用类型, 是通过 proto(隐式原型一层一层往上找, 能否找到对应构造函数的 prototype)
3. 写一个原型链继承的例子
- function Element(ele) {
- this.ele = document.getElementById(ele);
- }
- Element.prototype.html = function(val) {
- var ele = this.ele;
- if (val) {
- ele.innerHTML = val;
- return this;
- } else {
- return ele.innerHTML;
- }
- };
- Element.prototype.on = function(type, fn) {
- var ele = this.ele;
- ele.addEventListener(type, fn);
- return this;
- }
- var element = new Element('main');
- element.html('hello').on('click', function() {
- alert('handleClick');
- });
4. 描述 new 一个对象的过程
创建一个新对象
this 指向这个新对象
执行代码给 this 赋值
- return this
- function Foo(name) {
- this.name = name;
- // return this; // 本身会执行这一步
- }
- var f = new Foo('shiyanping');
来源: http://www.jianshu.com/p/0688e579c148