0

I have several div with the same "album" class, so I wanted to create a class using constructor and prototype. Here's what I did

function Album(album){
    this.album = album;

    console.log(this.album === album)
    console.log($(this.album) === $(album))
}

Album.prototype = {
    init: function(){

    },

    loadImages: function(){

    }
};

$('.album').each(function(){    
    var album = new Album(this);
});

I need to access the album variable that I passed in to the class Album in the init function, so I have to store it in this.album. However I don't understand that why console.log(this.album === album) is true but console.log($(this.album) === $(album)) is false

I need to use jquery in prototype, is there other way to do so? Thanks.

1
  • $(this.album).get(0) === $(album).get(0) should also return true if this.album === album returns true. But each time you wrap a DOM element inside the jQuery notation (with $) you will get a new reference, like Alex Wayne explained below. Commented Nov 7, 2012 at 2:02

1 Answer 1

3
$('body') === $('body') // false

Basically, you are doing this right. jQuery is screwing with you.

With objects the === operator is only true if it is the same object. In this case, jQuery makes a brand new object each time it wraps a DOM element, making a new object even if it's wrapping the same element it did a second ago.

Here's an example of why this is in plain JS, without jQuery:

var domEl = document.getElementById('whatev');
var a = { el: domEl };
var b = { el: domEl };

domEl === domEl // true
a === b         // false

Here there is 2 objects, both have identical data and wrap the same object. But they are different objects and therefore not === to each other.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.