I decided for myself to understand the simple principle of jQuery and ran into a problem. When I try to organize a simplified version of the library, I cannot call the functions that lie inside the function. Code example:

var jQ = function(el) { this.el = document.getElementById(el); } jQ.prototype.html = function(text){ this.el.innerHTML = text; return this; } jQ.prototype.css = function(key, value){ this.el.style[key] = value; return this; } // Использование jQ('bar').html('test'); 
  • 2
    you made a constructor function, but use it as a normal function, don't do it like that Before calling, add new : new jQ('bar').html('test'); - Grundy

1 answer 1

 function extend(Child, Parent) { var F = function() { } F.prototype = Parent.prototype Child.prototype = new F() Child.prototype.constructor = Child Child.superclass = Parent.prototype } // создали базовый класс var parent = function() {}; // создали класс // и сделали его потомком базового var jQ = function(el) { this.el = document.getElementById(el); } extend(jQ, parent); // добавили в класс parent методы и свойства parent.prototype.html = function(text){ this.el.innerHTML = text; return this; }; parent.prototype.css = function(key, value){ this.el.style[key] = value; return this; }; // Использование var element = new jQ('bar'); element.html('test'); 

In more detail about inheritance you can read:

https://learn.javascript.ru/class-inheritance

http://javascript.ru/tutorial/object/inheritance

  • one
    but what about the inheritance, if the question is simply forgotten new - Grundy
  • @Grundy, Yes, I know, but there is a problem =). And if I want to work with many elements, as in jquery. To change the selector, you need to constantly create an object through new? - Node_pro
  • @ AlekseyFursov, yeah, if you look at the jQuery function itself, you will see that it is an object and returns it, each time - Grundy
  • @Grundy, As I understand it, the jQuery code is as follows: $('.element').css('width'); $('.element2').css('width'); $('.element').css('width'); $('.element2').css('width'); . And I get $ = new Jq('.element1'); $.css('width'); $ = new Jq('.element2'); $.css('width') $ = new Jq('.element1'); $.css('width'); $ = new Jq('.element2'); $.css('width') $ = new Jq('.element1'); $.css('width'); $ = new Jq('.element2'); $.css('width') - Node_pro
  • @ AlekseyFursov, this is a topic for a separate big question :-) in two words: function jQuery() { return new jQuery.fn.init(); } function jQuery() { return new jQuery.fn.init(); } therefore it is called without new - Grundy