我正在尝试学习如何在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
。
答案 0 :(得分:1)
没有必要使用不标准的__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的原型。
答案 1 :(得分:0)
您需要将实际构造函数prototype
Jo.init
设置为您要使用的原型对象。此外,如果您想在Jo.infos()
函数本身而不是实例上调用Jo
,则必须将其放在那里而不是原型上。
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";
};
答案 2 :(得分:0)
我终于找到了解决方案:
(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 );
答案 3 :(得分:-1)
__proto__
是查找链中用于解析方法的对象
prototype
是用新的
__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;
};