naresh kumar
naresh kumar

Reputation: 2241

JavaScript custom method

I have created a custom object and added a method to it which is called changeColor with an attribute. The idea is when I attach this method to any DOM element that elements all content color must change.

Here is my started code:

function CustomColor() {

}

CustomColor.prototype.changeColor = function(color){
   //here what I have to specify.

}

This is pretty basic but I am new to JavaScript. Thanks.

Upvotes: 4

Views: 7163

Answers (3)

Rustam Nuriddinov
Rustam Nuriddinov

Reputation: 1

You must use the name local inside a function or object.

let ob = {
    theif : 'Davron',
    height : 1.7,
    color : {
        hair : 'qora',
        esee : 'white',
    },

    methodName: function () {
        return 'This is medthod';
    }
}

console.log(ob.methodName());

Upvotes: 0

Teemu
Teemu

Reputation: 23396

I suppose this is what you're looking after:

var elem = document.getElementById('some_element'),
    CustomColor = function (element) {
        this.htmlElement = element;
    };
CustomColor.prototype.changeColor = function (color) {
    this.htmlElement.style.color = color;
    return;
};
elem.customColor = new CustomColor(elem);

Using attached property:

elem.customColor.changeColor('#00f');

Only way to get a reference to the hosting HTML element is to pass it as an argument to the constructor. However, in changeColor you can't refer any "private" variable of CustomColor (including its arguments), hence you'll need to create a "public" property for all those properties you want to use in changeColor. More info at MDN

A live demo at jsFiddle.

The code above creates a custom property only to a specific HTML element. It's not recommended to create custom properties to the prototype of a DOM element, since those are not supported in all browsers.

Upvotes: 2

Shlomi Komemi
Shlomi Komemi

Reputation: 5545

use CustomColor like this:

function CustomColor(element) {
    this.element = element;
}
CustomColor.prototype.changeColor = function (color) {
    this.element.style.color = color;
}

new instance of CustomColor:

var element = new CustomColor(document.body);
element.changeColor('red');

you can also extend the actual dom element without using any extra classes like this:

Element.prototype.changeColor = function (color) {
    this.style.color = color;
};

and use it like this:

document.body.changeColor('red')

Upvotes: 5

Related Questions