javascript中的链接问题
我有以下问题,我正在尝试制作一个小链子javascript中的链接问题,javascript,jquery,object,chaining,Javascript,Jquery,Object,Chaining,我有以下问题,我正在尝试制作一个小链子 (function(window){ window.de=de={} de.one=function(s){if(s){var y=document.getElementById(s); return y;} return this;} de.two=function(s2){alert(s2); return this;} })(window) 这就是我试图做到的: de.one("Id").two("Hello!"); 但是控制台给了我这个错
(function(window){
window.de=de={}
de.one=function(s){if(s){var y=document.getElementById(s); return y;} return this;}
de.two=function(s2){alert(s2); return this;}
})(window)
这就是我试图做到的:
de.one("Id").two("Hello!");
但是控制台给了我这个错误:
TypeError:Object#没有方法'two'控制台没有说谎
HTMLElement
没有名为two
的方法,因为该方法属于window.de
不要通过添加到宿主对象的原型来修改宿主对象,如HTMLElement
。它们不是用JavaScript实现的
编写一个包含方法的包装器,类似于jQuery:
(function(window) {
var de = function(thing) {
return new de.prototype.init(thing);
};
de.prototype = {
constructor: de,
init: function(thing) {
this.thing = thing;
},
one: function(other) {
return de(other);
}
};
de.prototype.init.prototype = de.prototype;
window.de = de;
})(window);
现在,您可以执行以下操作:
de('foo').one('bar').one('bar').one('baz')
您不能这样做,问题是在de.one()中,您有两种不同类型的返回值 “返回y”并返回“this”。如果你想连锁,你必须“这个”。给你一个想法:
(function(window){
var myLibrary = (function( s ) {
var d = document,
e = d.getElementById( s ),
methods = {
one : function(val){
alert(val);
return this; // maintain chainability
},
two : function(val){
alert(val);
return this; // maintain chainability
},
css : function( property, val){
if(!val && typeof property == "object" ){ // styles in Object notation
for(var key in property){
e.style[key] = property[key];
}
}else{ // Comma separated: property, value
e.style[property] = val || undefined;
}
return this;
}
};
return methods;
});
window.myLibrary = window.de = myLibrary; // Make Window accept "de" as "myLib" alias.
})(window);
考虑到您有以下情况:
<div id="Id">Some element</div>
某个元素
您返回的是y(html元素),而不是此
谢谢您的朋友,谢谢您的帮助谢谢您的朋友,谢谢您的帮助
<div id="Id">Some element</div>