Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Programming

    1. Express.js Lessons. Basics and Middleware. Part 1.

    B2B Leads

    Effective Strategies to Boost B2B Lead Conversion Rates

    Interview

    Behavioral Interview 101: How to Tackle the Toughest Questions | Sample Answers Included

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Tuesday, September 9
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / Programming / 6. Уроки Node.js. Util и Наследование
    Programming

    6. Уроки Node.js. Util и Наследование

    bragin_paBy bragin_paSeptember 9, 2016Updated:May 26, 2024No Comments4 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    6. Уроки Node.js. Util и Наследование
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    nodejs_logo_green

    Всем привет! Тема ближайших статей: Самые часто используемые модули Node.js.

    Первым методом, который мы изучим, будет метод util inspect модуля, встроенного util. Этот метод позволят красиво вывести любой объект, даже если у этого объекта, как в этом примере, есть ссылка на самого себя.

    var util = require('util');  
      
    var obj = {  
      a: 5,  
      b: 6,  
    };  
    obj.self = obj;  
      
    console.log( util.inspect(obj) ); 
    

    Запускаем node inspect.js и видим, что, действительно, все красиво обработалось. При этом, если у объекта есть свойства inspect, и оно равно функции, то эта функция будет вызвана.

    var util = require('util');  
      
    var obj = {  
      a: 5,  
      b: 6,  
      inspect: function() {  
        return 123;  
      }  
    };  
    obj.self = obj;  
      
    console.log( util.inspect(obj) );  
    

    Именно ее результат будет возвращен. Например, я сделал функцию inspect и вернулся 123. Таким образом, поведение метода util inspect несколько напоминает toString. И этот метод используется в console автоматически, если она хочет добавить в log какой-то объект. Я убрал util inspect:

    var util = require('util');  
      
    var obj = {  
      a: 5,  
      b: 6,  
      inspect: function() {  
        return 123;  
      }  
    };  
    obj.self = obj;  
      
    console.log(obj);
    

    Вызываю. Все работает так же. Потому что, на самом деле, console вызывает его внутри. Однако, иногда все же необходимо обращаться к util inspect явно, в первую очередь, в тех случаях, когда мы хотим вывести что-то не в console, а, например, получить строчное представление объекта для вывода в файл. Кроме того, есть дополнительные параметры util inspect: можно, например, задать глубину вывода объекта, по умолчанию два. Но они используются редко.

    Следующая команда – это  util format. Создадим файл format.js.

    var util = require('util');  
    var str = util.format("My %s %d %j", "string", 123, {test: "obj"});   
      
    console.log(str);
    

    Util format получает строку и дальше оно подставляет в нее следующие параметры. Вместо  %s будет выведена строка, вместо %d будет выведено число, а далее вместо %j будет выведен объект в формате json. Если я сейчас это запущу, то вот что я получу:

    Read More:  13. Уроки Node.js. Разработка, supervisor

    {“text”:”obj”}

    Обратите внимание, это формат json. Это не вывод util inspect. Соответственно, если вдруг я вместо числа передал здесь что-то еще, то при выводе я получу NaN, потому что автоматически происходит конвертация.

    Метод util format также используется в console не явно. Если я сейчас возьму и перенесу это прямо в консоль:

    var util = require('util');  
    var str = util.format("My %s %d", "string", 123, {test: "obj"});   
      
    console.log(str);
    

    то все отлично продолжит работать:

    var util = require('util');  
      
      
    console.log("My %s %d", "string", 123, {test: "obj"}); 
    

    Следующий, последний метод util, о котором пойдет речь – это метод util inherits. Чтобы его было легче понять, я позволил себе скачать исходники Node.js и достать из них файл util.js. Это как раз и есть исходник модуля util. И там на чистом java script есть метод inherits:

    exports.inherits = function(ctor, superCtor); {  
    ctor.super_ = superCtor  
    ctor.prototype = Object.create(superCtor.prototype, {  
    constructor: {  
    value:ctor,  
    enumerable:false,  
    writable:true,  
    configurable:true  
    }  
    });  
    }; 
    

    Если вы знаете, как работает OOP в JavaScript, тогда вы этот метод сразу понимаете. Если же нет, то рекомендуется разобраться с этим. Впрочем, использовать его одно и так довольно просто. Достаточно создать родительский класс, конструктор, методы в прототипе.

    var util = require('util');  
      
    // Parent  
    function Animal(name) {  
      this.name = name;  
    }  
      
    Animal.prototype.walk = function() {  
      console.log("Running " + this.name);  
    };  
    

    Затем, чтобы унаследовать от него, создаем конструктор потомка и вызываем util inherits:

    // Потомок  
    function Rabbit(name) {  
      this.name = name;  
    }  
      
    util.inherits(Rabbit, Animal);
    

    Потом добавляем в прототип методы:

    Rabbit.prototype.jump = function() {  
      console.log("Jumping " + this.name);  
    };  
    

    Получается, что все объекты, создаваемые этим конструктором, будут наследовать от Animal. Так что если я сейчас запущу код node inherits.js, то rabbit.walk сначала вызовет метод родителя, а rabbit.jump вызовет метод потомка. Все как обычно при наследовании:

    var util = require('util');
    
    // Parents
    function Animal(name) {
        this.name = name;
    }
    
    Animal.prototype.walk = function() {
        console.log("Running " + this.name);
    };
    
    // Child
    function Rabbit(name) {
        this.name = name;
    }
    
    util.inherits(Rabbit, Animal);
    
    Rabbit.prototype.jump = function() {
        console.log("Jumping " + this.name);
    };
    
    // Usage
    var rabbit = new Rabbit("rabbit");
    rabbit.walk();
    rabbit.jump();
    

    Код данного урока можно скачать отсюда.

    Read More:  23. Уроки Node.js. Домены, "асинхронный try..catch". Часть 2.

    More-To-Come-Soon

    Материал урока взят из следующего скринкаста.

    We are looking forward to meeting you on our website blog.soshace.com

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    bragin_pa

      Related Posts

      3. Уроки Express.js. Шаблонизация с EJS: Layout, Block, Partials

      December 16, 2016

      Уроки Express.js . Логгер, Конфигурация, Шаблонизация с EJS. Часть 2.

      December 2, 2016

      2. Уроки Express.js . Логгер, Конфигурация, Шаблонизация с EJS. Часть 1.

      November 24, 2016

      Comments are closed.

      Stay In Touch
      • Facebook
      • Twitter
      • Pinterest
      • Instagram
      • YouTube
      • Vimeo
      Don't Miss
      PHP February 3, 2020

      Top 6 Features of PHP 7.4 – Explained with Examples

      PHP 7.4 is a minor version, but it includes plenty of new features. Here I show you the top 6 of them with examples. They can make a significant effect on your PHP development process.

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Build Real-World React Native App #9 : Implementing Remove Ads Feature

      January 19, 2021

      Disadvantages of Using TypeScript

      May 31, 2019

      Categories

      • AI & Automation
      • Angular
      • ASP.NET
      • AWS
      • B2B Leads
      • Beginners
      • Blogs
      • Business Growth
      • Case Studies
      • Comics
      • Consultation
      • Content & Leadership
      • CSS
      • Development
      • Django
      • E-commerce & Retail
      • Entrepreneurs
      • Entrepreneurship
      • Events
      • Express.js
      • Facebook Ads
      • Finance & Fintech
      • Flask
      • Flutter
      • Franchising
      • Funnel Strategy
      • Git
      • GraphQL
      • Home Services Marketing
      • Influencer & Community
      • Interview
      • Java
      • Java Spring
      • JavaScript
      • Job
      • Laravel
      • Lead Generation
      • Legal & Compliance
      • LinkedIn
      • Machine Learning
      • Marketing Trends
      • Medical Marketing
      • MSP Lead Generation
      • MSP Marketing
      • NestJS
      • Next.js
      • Node.js
      • Node.js Lessons
      • Paid Advertising
      • PHP
      • Podcasts
      • POS Tutorial
      • Programming
      • Programming
      • Python
      • React
      • React Lessons
      • React Native
      • React Native Lessons
      • Recruitment
      • Remote Job
      • SaaS & Tech
      • SEO & Analytics
      • Soshace
      • Startups
      • Swarm Intelligence
      • Tips
      • Trends
      • Vue
      • Wiki
      • WordPress
      Top Posts

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      Medical Marketing August 27, 2025

      Уроки React . Урок 8

      Programming September 30, 2016

      Interview With Oleg – Soshace Team

      Interview December 8, 2016

      RxJs Practice

      Programming April 26, 2017

      Subscribe to Updates

      Get The Latest News, Updates, And Amazing Offers

      About Us
      About Us

      Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

      7901 4th St N, Suite 28690
      Saint Petersburg, FL 33702-4305
      Phone: 1(877)SOSHACE

      Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
      Our Picks
      Trends

      4 Tech Factors Driving the World Economy of Tomorrow

      JavaScript

      Bootstrap your next Preact application with Bun

      JavaScript

      React Lesson 11. Pt.1: Normalize Comments with Immutable.js

      Most Popular

      11 Best Books on DevOps: Comprehensive Overview

      Beginners

      Anime.js to MP4 and GIF with Node.js and FFMPEG

      Express.js

      21. Уроки Node.js. Writable Поток Ответа res, Метод pipe. Pt.2

      Programming
      © 2025 Soshace Digital.
      • Home
      • About
      • Services
      • Contact Us
      • Privacy Policy
      • Terms & Conditions

      Type above and press Enter to search. Press Esc to cancel.