jQuery的封装方式与JS中new的实现原理
function jQuery() { return new jQuery.fn.init(); } jQuery.fn = jQuery.prototype = { init: function() { return this; }, showName: function() { console.log(this.name); return this; }, showAge: function() { console.log(this.age); return this; }, age: 13, name: "aaa" } jQuery.prototype.init.prototype = jQuery.prototype; jQuery().showAge().showName();//链式调用
var Base = function(name) { this.name = name; } Base.prototype.get_name = function() { return this.name; } //方式一 var obj = new Base("pcd"); var name = obj.get_name(); console.log(name);//pcd //方式二 var obj = {};//创建一个obj对象 obj.__proto__ = Base.prototype;//将obj的原型指向Base.prototype Base.call(obj,"pcd");//将Base中的this指向obj var name = obj.get_name(); console.log(name);//pcd