function instance is causing confusion with the hasOwnProperty() method

When looking at the code example provided, it is interesting to note that the doOtherStuff function is defined directly on the b instance, rather than being higher up in the prototype chain (like on base or Object). This leads to a situation where b.hasOwnProperty('doOtherStuff') returns false. Why might this be the case?

var base = (function () {

    var cls = function () { };

    cls.prototype.doStuff = function () {
        console.log('dostuff');
    };

    return cls;

})();

var child = (function () {

    var cls = function () {
        base.call(this);
    };

    cls.prototype = Object.create(base.prototype);
    cls.prototype.constructor = child;

    cls.prototype.doOtherStuff = function () { // <--
        console.log('doOtherStuff');
    }

    return cls;

})();

var b = new child();

console.log(b.hasOwnProperty('doOtherStuff'), 'doOtherStuff' in b); //false true

http://jsfiddle.net/5FzBQ/

Answer №1

Seeing as the function doOtherStuff is actually declared directly on the instance b

No, that statement is incorrect; you actually defined that property within cls.prototype.

hasOwnProperty() will only return true if you assign using this.property = ... (or access through b.property).

Answer №2

When looking at the code, it's important to note that doOtherStuff is not explicitly defined within the b object; rather, it is inherited from its prototype. The function hasOwnProperty helps distinguish between properties that are directly defined on an object versus those inherited from the prototype, whereas the in operator does not provide this distinction.

To learn more, you can visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Attempting to retrieve a refresh token from the Google API resulted in an Uncaught ReferenceError, as the

I am currently working on obtaining a refresh token once a user authorizes with Google in order to prevent the need for re-authorization. After studying Google's documentation, I learned that setting the access type to offline is necessary. Now, I am ...

What is the best way to set up a server in React using Express or HTTP?

I am currently in the process of developing a web application using react js. In order to create a server for my client within the project, I have decided to utilize either express or http. Here is the code snippet that I attempted: import React from " ...

Error: An issue occurred with the tasks in the Gruntfile.js file

pm WARN EPACKAGEJSON <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74041506001a1106041b0600151834445a445a44">[email protected]</a> No description npm WARN EPACKAGEJSON <a href="/cdn-cgi/l/email-protection" ...

How to Use Google Calendar API to Retrieve Available Time Slots for a Given Day

Is there a way to extract the list of available time slots from my Google Calendar? Currently, I am only able to retrieve the list of scheduled events. I am utilizing the Google Calendar npm package. google_calendar.events.list(calObj.name,{ timeMin ...

Positioning Multi-level Drop Down Div in Javascript - How to do it efficiently?

I'm currently working on a horizontal menu using CSS and JavaScript with multiple levels. I've implemented a toggle function to show the submenu container, but it's causing the links below it to be pushed down. Is there a way to make the dis ...

Using VueJs to invoke a plugin from a .js file

I'm seeking a deeper understanding of working with vueJS. My current setup In my Login.vue component, there is a function logUser() from UserActions.js which in turn calls the postRequest() function from AxiosFacade.js Additionally, I use a plugin ...

The Vue.js Vuetify.js error message is saying "A mystery custom element: <v-list-item>, <v-list-item-title> - Have you properly registered the component?"

I followed the instructions from Vuetify Data Iterator Filter section I am able to use various Vuetify components like v-btn, v-card, v-data-table, v-data-iterator, and more. However, I encountered errors only with <v-list-item> and <v-list-item ...

Javascript and the output of Ajax request

I'm facing an issue with my JavaScript files interacting with the response from an ajax request. It seems that the JavaScript is unable to read the response from the ajax call. My question is, how can I get my jQuery plugin to access the classes in t ...

jQuery UI Sortable: Efficiently Drag Items Across Multiple Interconnected Lists

One feature of using jQuery UI Sortable is the ability to make the sortable item container scroll when an item is dragged. This can be achieved by specifying the scroll option. In my case, I have several sortable lists that are connected within separate c ...

What's the best way to showcase array values in JavaScript?

I am facing an issue where I am trying to display all values from the array "categories", but I keep getting [object object] or undefined. The problem seems to be occurring in the code within the last lines of the if statement, specifically when I try to ...

Using VueLoaderPlugin() results in an 'undefined error for 'findIndex' function

Currently, I am in the process of integrating a Vue CLI app into another web project that we are actively developing. The Vue app functions without any issues when utilizing the development server bundled with Vue CLI. Due to the presence of .vue files wi ...

Issue encountered when attempting to utilize Next-Auth alongside Credentials Provider to authenticate within a pre-existing system

I am currently utilizing the Next-Auth Credentials provider for authentication purposes through our existing API. Following the guidelines provided at https://next-auth.js.org/configuration/callbacks the code snippet used is as follows: callbacks: { ...

Exploring the Concept of Nested ViewModels in Knockout.js Version 3.2.0

I have a global view model that is applied to the main div and I also have other view models that I want to apply to nested elements within my main div However, I am encountering an issue: You cannot bind multiple times to the same element. Below is ...

Methods for removing and iterating through images?

I successfully programmed the image to move from right to left, but now I want to add a function where the image is deleted once it reaches x: 50 and redrawn on the left. I attempted to use control statements like "if," but unfortunately it did not work a ...

What is the process of transforming a string into an angular binding?

I have a variable called message that contains the text "you are moving to {{output.number}}". I attempted to insert this into a div element using $("#message").html(message); However, it just displayed the entire string without replacing {{output.number ...

utilizing angularjs and bootstrap to manage multiple button models

Recently delved into learning angularjs and bootstrap. Found a tutorial on creating buttons. <div ng-controller="ButtonsCtrl"> <h4>Checkbox</h4> <pre>{{checkModel}}</pre> <div> <button type="butto ...

Refreshing certain sections of a webpage without the need to refresh the entire page

If you want to understand better, it would be helpful if you could check out my website first at: The main part of the website is a stream from Own3D.tv displayed through an iframe (line 342). My objective is to have the ability to click on a specific str ...

Creating an array of objects in Javascript by setting two different values as a range

Given an array of objects structured as follows: [{value: "a", start: 1950, end: 1954, description: "aaa"}, {value: "b", start: 1953, end: 1956, description: "bbb"}, {value: "c", start: 1960, end: 1962, des ...

Automatic capitalization feature for input fields implemented with AngularJS

I have integrated a directive into my input field to validate a license key against a server-side API. While this functionality works well, I also want the license key to automatically add hyphens and appear in capital letters. For example, when a user in ...

Creating background color animations with Jquery hover

<div class="post_each"> <h1 class="post_title">Single Room Apartments</h1> <img class="thumb" src="1.jpg"/> <img class="thumb" src="1.jpg"/> <img class="thumb" src="1.jpg"/> <img class="thumb last" ...