這篇文章主要說原型及原型鏈,鑑戒了一些網絡大神的想法,有什麼疑問可以提出來大家一起共同解決
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');
閱讀更多 浮生偷閒 的文章