views:

32

answers:

2

Hey. I have no idea why i get a 'b' and not an 'a' when i call a.get(). Can someone help me?

var tclass = new Class({
initialize:function(n){
    this.options = Object.extend({'name' : n});
},
get:function(){
    return this.options.name;
}
});

a = new tclass('a');
b = new tclass('b');
a.get()  // b
A: 

Shouldn't you use the new operator line 3 ?

this.options = (new Object()).extend({'name' : n});
Golmote
no, this is not right. he's using the mootools 1.3 api calling to the Object prototype
Dimitar Christoff
YES baby, that's it (mootools 1.11) ! I missed the wood for the trees.
sumflow
oh dear. i will go away now. check revised example via the Options mixin and mootools 1.11 (from http://docs111.mootools.net/Class/Class-Extras.js)
Dimitar Christoff
+3  A: 

you should use the Options class as a mixin and the setOptions to do the merge properly:

var tclass = new Class({
    Implements: [Options],
    initialize: function(n) {
        this.setOptions(n);
    },
    get: function() {
        return this.options.name;
    }
});


var a = new tclass({
    name: 'a'
});
var b = new tclass({
    name: 'b'
});
alert(a.get()); // a

having said that, in your example i get a different response - as expected - but via $merge and not extend (merge does unlink): http://www.jsfiddle.net/dimitar/cqd8P/

yet what's the point in this as you have no this.options that exists (you need to pass on an object to extend it / merge it with another one). you may as well just do:

this.options = {
    name: n
};

you really want this.setOptions

p.s. for mootools 1.11 Implements is done differently:

var tclass = new Class({
    initialize: function(n) {
        this.setOptions(n);
    },
    get: function() {
        return this.options.name;
    }
});

tclass.implement(new Options);

var a = new tclass({
    name: 'a'
});
var b = new tclass({
    name: 'b'
});
alert(a.get()); // a
Dimitar Christoff
Dimitar you're a machine.
Chase
heh, hardly, mootools gets like 3-4 questions a week here, hardly taxing to spare 5 mins and answer (if you think know the answer anyway, that is), is it :) i find having to consider other people's problems a great way to learn
Dimitar Christoff