如何使用原型进行自定义方法和对象操作 [英] How to use prototype for custom methods and object manipulation

查看:33
本文介绍了如何使用原型进行自定义方法和对象操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

老实说,我正在尝试理解 JavaScript 原型,但并没有取得太大进展.我不太确定如何解释我想要做的事情,只是说我的最终目标部分是学习如何像 jQuery 一样遍历 DOM 并添加自定义方法来操作正在访问的特定元素.

Honestly, I am trying to understand JavaScript prototypes and I'm not making much progress. I am not exactly sure how to explain what I am trying to do, except to say that in part my end goal is to learn how to traverse the DOM similar to jQuery and to add custom methods to manipulate particular elements being accessed.

下面的代码已更新,以反映我从迄今为止收到的答案中学到的概念,并显示出那些与我想要完成的目标相去甚远的地方.

EDIT : The code below has been updated to reflect concepts I have learned from the answers received so far, and to show where those fall short of what I am looking to accomplish.

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;

在可能的情况下,请解释您的代码为何有效,以及为什么您认为这是实现此目的的最佳方法.

Where possible please add an explanation of why your code works and why you believe it is the best possible method for accomplishing this.

注意:我询问的全部目的是为了自己学习...请不要建议使用jQuery,它违背了目的.

Note: The whole purpose of my inquiry is to learn this on my own... please do not suggest using jQuery, it defeats the purpose.

推荐答案

var $ = function(id) {  
    return new My_jquery(id);  
}  

function My_jquery(id) { 
    this.elem = document.getElementById(id);
}

My_jquery.prototype = {
   insert : function(text) { this.elem.innerHtml = text; return this;}
}

$('para1').insert('hello world').insert('chaining works too');  

在 My_jquery.prototype 中添加任何你想操作 elem 的方法

add any method u want to operate on elem in My_jquery.prototype

这篇关于如何使用原型进行自定义方法和对象操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆