<!-- 理解原型 --> <script> function Person(name){ this.name=name } Person.prototype.age=10 var person1 = new Person() var person2 = new Person() console.log(person1.age) console.log(person2.age) // 实例的原型属性和构造函数的原型对象指向同一个对象 console.log(person1.__proto__) console.log(Person.prototype) console.log(person1.__proto__ === Person.prototype) //true // 构造函数的原型属性也是一个对象,也可以有属于自己的原型 console.log(Person.prototype.__proto__) console.log(Person.prototype.__proto__.constructor) //Object console.log(Person.prototype.__proto__ === Object.prototype) console.log(Person.prototype.__proto__.__proto__) //null console.log(Person.hasOwnProperty('name')) // var a=[1,2] // console.log(a.__proto__) // console.log(a.hasOwnProperty('aaa')) </script>
2.原型的实际运用:
jquery和zepto这两个库就是用原型实现的,模拟一下
(function (window) { var jQuery = function (selector) { return new jQuery.fn.init(selector) } jQuery.fn = { css: function (key, value) { alert('css') }, html: function (value) { return 'html' } } var init = jQuery.fn.init = function (selector) { var slice = Array.prototype.slice var dom = slice.call(document.querySelectorAll(selector)) var i, len = dom ? dom.length : 0 for (i = 0; i < len; i++) { this[i] = dom[i] } this.length = len this.selector = selector || '' } init.prototype = jQuery.fn window.$ = jQuery })(window)
原型的扩展怎么扩展的?
<script type="text/javascript" src="./jquery-3.2.1.js"></script> <script type="text/javascript"> // 插件扩展 $.fn.getNodeName = function () { // this alert(this[0].nodeName) } </script> <script type="text/javascript"> // 验证 var $p = $('p') $p.getNodeName() var $div1 = $('#div1') $div1.getNodeName() </script>