Js. New way of creating methods in objects

// lets say we have some object here
let range = {
    from: 1,
    to: 5
}

range['anyMethod'] = function(){
    return 'hi from new way of creating method';
}

console.log(range.anyMethod());

// lets do the iteration from 1 to 5

range[Symbol.iterator] = function () {
    return {
        current: this.from,
        last: this.to,
        next() {
            if (this.current <= this.last) {
                return {done: false, value: this.current++}
            } else
                return {done: true}
        }
    }
}

// now let's iterate
for (let num of range){
    console.log(num)
}


This entry was posted in Без рубрики. Bookmark the permalink.