老实说,我正在尝试理解 JavaScript 原型,但并没有取得太大进展。我不完全确定如何解释我正在尝试做什么,除了说我的最终目标部分是学习如何遍历类似于 jQuery 的 DOM 并添加自定义方法来操作正在访问的特定元素。
编辑:下面的代码已经更新,以反映我从迄今为止收到的答案中学到的概念,并显示那些没有达到我想要完成的目标。
function A(id) {
"use strict";
this.elem = document.getElementById(id);
}
A.prototype.insert = function (text) {
"use strict";
this.elem.innerHTML = text;
};
var $A = function (id) {
"use strict";
return new A(id);
};
var $B = function (id) {
"use strict";
return document.getElementById(id);
};
function init() {
"use strict";
$A('para1').insert('text goes here'); //this works
$A('para1').innerHTML = 'text goes here'; //this does not work
console.log($A('para1')); //returns the object A from which $A was constructed
console.log($B('para1')); //returns the dom element... this is what I want
/*I want to have $A('para1').insert(''); work and $A('para1').innerHTML = '';
work the same way that $B('para1').innerHTML = ''; works and still be able
to add additional properties and methods down the road that will be able
act directly on the DOM element that is contained as $A(id) while also
being able to use the properties and methods already available within
JavaScript*/
}
window.onload = init;
在可能的情况下,请解释为什么您的代码有效,以及为什么您认为这是实现此目的的最佳方法。
注意:我查询的全部目的是自学……请不要建议使用 jQuery,它违背了目的。