【问题标题】:create object prototype callable has object and function创建对象原型可调用具有对象和功能
【发布时间】:2013-10-15 02:55:02
【问题描述】:
我正在尝试学习如何在 js 中使用原型。
第一个问题:
我想在 jQuery 中做一个类似$() 的函数。
当我这样称呼它Jo("header h1") 时,它可以工作,但当我调用Jo.infos() 时就不行。
var Jo = function( selector ){
return new Jo.init(selector);
};
Jo.prototype = {
infos: function(){
return "Hello! I'm Jo, I'm here to make your life easier";
}
};
Jo.init = function( selector ){
this.selector = selector;
};
我的错误在哪里,如何解决?
第二个问题:
返回的对象是Jo.init,但我想要Jo。
【问题讨论】:
标签:
javascript
javascript-framework
【解决方案1】:
我终于找到了我的解决方案:
(function( window, undefined ){
var Jo = function( selector, context ){
return new Jo.fn.init(selector, context);
};
Jo.fn = Jo.prototype = {
Jo: "0.1",
constructor: Jo,
init: function( selector, context ){
console.log( "$() request work" );
}
};
Jo.infos = function(){
console.log("info work");
};
Jo.fn.init.prototype = Jo.fn;
if( typeof window === "object" && typeof window.document === "object" ) window.Jo = window.$ = Jo;
})( window );
【解决方案2】:
您需要将实际构造函数Jo.init 的prototype 设置为您要使用的原型对象。此外,如果您想在 Jo 函数本身而不是实例上调用 Jo.infos(),则必须将其放置在那里而不是原型上。
function Jo(selector) {
return new Jo.init(selector);
}
Jo.init = function(selector) {
this.selector = selector;
};
Jo.init.prototype = Jo.prototype = {
// instance methods here
…
}
Jo.infos = function(){
return "Hello! I'm Jo, I'm here to make your life easier";
};
没有额外的init 函数:
function Jo(selector) {
if (! (this instanceof Jo)) return new Jo(selector);
this.selector = selector;
}
Jo.prototype = {
// instance methods here
…
}
Jo.infos = function(){
return "Hello! I'm Jo, I'm here to make your life easier";
};
【解决方案3】:
没有必要使用不标准的__proto__。
使用这个:
var Jo = function( selector ){
this.init(selector);
};
Jo.prototype = {
infos: function(){
return "Hello! I'm Jo, I'm here to make your life easier";
},
init : function( selector ){
this.selector = selector;
},
constructor : Jo //reset constructor, because we are using object literal which override the original prototype object
};
var jo = new Jo('jojo');
console.log(jo instanceof Jo); //return true
console.log(jo.infos()); //display the Hello....
在您的代码中,您创建的实例是 Jo.init 的一个实例,因为您显式地返回了一个新对象。所以这个实例无权访问 Jo 的原型。
【解决方案4】:
__proto__ 是在查找链中用于解析方法的对象
prototype 是用于在您使用 new 创建对象时构建 __proto__ 的对象
var Jo = function( selector ){
return new Jo.init(selector);
};
Jo.__proto__= { //<--------------------- __proto__
infos: function(){
return "Hello! I'm Jo, I'm here to make your life easier";
}
};
Jo.init = function( selector ){
this.selector = selector;
};