Why do object == this, but object.member != this.member in the realm of Javascript?

I currently have an object labeled o along with a reference to it.

Inside the scope of object o, I define a member named m.

Within object o, I execute:

o.m = "blah"

When I try to access m outside of object o:

console.log(o.m)

The output is not "blah". To investigate, I ran:

console.log(this == this.parent.o)

This statement evaluates to true. I am puzzled by this behavior. My browser is Chrome 17.0.963.56 m

UPDATE

I also experimented within object o:

this.m = "blah"
console.log(this.m) // prints "blah"

However, upon exiting that context and running:

console.log(o.m)

The result is different.

Below is the relevant code snippet (refer to this.addEvent("playPauseButtonClicked")):

    // Controller code (singleton)
    function controller() {
        if (window.c) { return window.c; }
        window.c = this;
    ...
    }

Answer №1

When working within the confines of o and trying to assign a value to m, the correct syntax would be:

this.m = "blah";

It is important to consider that within o, the scope of o may have been set differently, leading to unexpected behavior.


UPDATE 2 -- It seems like the OP has revised their question, so the following code might no longer be applicable -- sigh


UPDATE

A couple of issues have been identified. Firstly:

this.p = new player();

Where your player constructor is defined as:

function player(controller) {
    this.controller = controller;

It appears that you are not passing anything for the controller parameter, resulting in the undefined error for p. Try the following instead:

this.p = new player(this);

Additionally, in your controller constructor, after assigning p as a property of the return object using this.p = new player(this), you should reference it as this.p moving forward; referencing just p will result in an undeclared variable. So

function controller() {
    this.p = new player(this);
    p.changeState();
    console.log(p.state);

should be updated to:

function controller() {
    this.p = new player(this);
    this.p.changeState();
    console.log(this.p.state);

Answer №2

It is essential to declare the variable before using it.

var x = new o; console.log(o.m);

Answer №3

If I were to make a modification:

this.player = new player(this);
this.player.changeState();
console.log(this.player.state);

Here are two key changes:

  1. player should be referenced with this.player instead of just player
  2. The player constructor now requires a controller parameter

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

Hover effect not displaying upon mouse exit

I am working on a feature where a series of images change when hovered over, with a div animating as an overlay on the image. Here is the code snippet: // hiding overlays initially $(".mini-shop .item .image a div").hide(); // toggling overlay and second ...

Incorporating promises with ajax to enhance functionality in change events

Consider the scenario where you trigger an ajax request upon a change event in the following manner: MyClass.prototype.bindChangeEvent = function(){ $(document).on('change', '#elementid', function(){ var $element = $(this); $ ...

Create a vibrant PNG image background that changes dynamically based on the dominant color of the

Is it possible to dynamically set the background color of a PNG image, either white or black, based on the dominant color in the image? For example, this image should have a dark background: https://i.stack.imgur.com/cerjn.png And this one should have a ...

Validating Linkedin URLs with JavaScript for Input Fields

I've created a basic form with an input field for a LinkedIn URL. Is there a way to validate that this field only accepts valid LinkedIn URLs? Thank you! ...

The issue arises when attempting to call a method from the same service within jsPDF in an Angular environment

Below you will find my Angular project's pdfService. I am facing an issue where calling the this.formatter() method inside myPDF is not functioning properly. export class pdfService { formatter(value: number): string { return new Intl.N ...

Is it feasible to retrieve information within a behavior in Drupal?

I recently installed the "Autologout" Drupal module, which can be found at . This module includes a timer that ends your session if there is no activity on the page for a set period of time. However, I am interested in adjusting the timer value to better ...

Seeking assistance with changing the pages

Looking for assistance with troubleshooting my function. All variables are accounted for. var swith = document.getElementById("sub"); var one = document.getElementById("rule"); var two = document.getElementById("cool"); var three = document.getElementByI ...

Reflector has no definition in three.js - a software mystery

After implementing the code snippet from the webgl_mirror example, I attempted to add a reflector surface to my scene. It seems that the following code snippet is all that's needed to introduce a reflective object to the scene: var geometry = new TH ...

Is submitting data through ajax giving you trouble?

As a beginner in PHP with no knowledge of Javascript, I have been relying on tutorials to complete my JS tasks. Despite trying various solutions from StackOverflow, I have yet to achieve success! My goal is to update database values by clicking the ' ...

Align Headers to the Top Center in React Material-UI Datagrid

Is there a way to align the wrapped headers at the top-center using sx? I've tried the following code: const datagridSx = { '& .MuiDataGrid-columnHeaders': { height: 'unset !important', maxHeight: '168p ...

Close ui-bootstrap typeahead menu only when a row is manually chosen

I have set up this jsBin to show the problem I am facing. When you visit the link and try to type "Five," the expected behavior would be to type "Five" and then press tab. However, in this case, you need to type "Five" and then either escape or click outsi ...

Having trouble retrieving data from the table with AJAX and CodeIgniter

I am currently developing a comprehensive HRM+CRM system (Human Resource Management and Customer Relation Management). I have encountered an issue while trying to generate an invoice for each customer. I am struggling to resolve this problem and would appr ...

Issues arise when using ng-repeat in conjunction with ng-click

I am facing some new challenges in my spa project with angularjs. This is the HTML snippet causing issues: <a ng-repeat="friend in chat.friendlist" ng-click="loadChat('{{friend.friend_username}}')" data-toggle="modal" data-target="#chat" d ...

Can you help me figure out how to retrieve the index of a CSS element during a 'click' event?

I have a collection of images all tagged with the class thumb. When a user clicks on one of these images, I need to determine which image was clicked within the array of thumbs. Essentially, I am looking for the index of the clicked image within the thumbs ...

Using percentages for sizing and margins in CSS

Looking to create a visually appealing page that always fills the entire screen? Check out this code snippet that does just that: #posts{ width:100%; height:auto; background:#666; } .entry{ float:left; margin-left: 4%; margin-top:10 ...

Initiate Child Event within Parent Component

Before switching tabs in the parent component, I want the child tab to validate itself. My idea is to pass the onActive event from the parent to its children, <ClientInfo/> and <Details/>. This will allow the children to validate themselves a ...

What could be causing "pointermove" events to have undefined movementX/Y on iOS?

After subscribing to "pointermove" events, I noticed that I am receiving events with undefined values for the movementX and movementY properties. I have tested this on both Chrome and Safari, but have not found any documentation regarding this issue in OS ...

What are the steps to start using the Intersection Observer API right away?

Utilizing the Intersection Observer API, I can accurately determine whether an element is within the viewport or not. Is there a way to utilize the Intersection Observer API to detect if an element is in the viewport without relying on a callback function ...

What is the best way to duplicate a tag that contains multiple other tags with attributes?

My form, named 'myForm', needs a div tag with the id 'original' to be added every time I click a button. Can someone help me figure out how to add these tags? The new tags should appear after the original one, but still within myForm. ...

Issue: The observer's callback function is not being triggered when utilizing the rxjs interval

Here is a method that I am using: export class PeriodicData { public checkForSthPeriodically(): Subscription { return Observable.interval(10000) .subscribe(() => { console.log('I AM CHECKING'); this.getData(); }); } ...