JavaScript - how to use "I" from the current JS class

I tried to create this syntax for JavaScript:

var user = new Class({
    name: 'No name',
    sayHello: function () {
        console.log(self.name);
    }
});

user.sayHello();  // will print "undefined" because "self" isn't visible

And I created this implementation Class:

function Class (_properties) {
    var self = this;

    // copy all properties and methods to this class
    for (var _property_name in _properties) {
        self[_property_name] = _properties[_property_name];
    }
}

But the problem is selfthat I want to use in every class. self.namewill be undefined because it selfis [Window object].


Question : how to change the code for use selfinside all functions in class instances? selfnecessary to not discard the context if the function is called from an external context.

Expected result (I mean that the code above should be executed as the code below):

function Class (_properties) {
    var self = this;

    // properties

    self.name = 'No name';

    // methods
    self.sayHello = function sayHello () {
        console.log(self.name);
    };
}

var user = new Class();
user.sayHello();

self, . , , , $.get('...', function () { console.log(this); }) - this . self ( magic), ( ).

+4
2

, , self sayHello, .

google JavaScript scope this tutorial - , , .

, self JavaScript , this is.

, , :

function Class (_properties) {

    // copy all properties and methods to this class
    for (var _property_name in _properties) {
        this[_property_name] = _properties[_property_name];
    }
}

var User = new Class({
    name: 'No name',
    sayHello: function () {
        console.log(this.name);
    }
});
var user1 = new User();
var user2 = new User();

new Class() , , this .

, sayHello , , this.name - this , new Class.

, ( , , , ) - ( ), global, Window.

+4

, :

var options = {
    name: 'No name',
    sayHello: function () {
        console.log(self.name);
    }
}
var user1 = new Class(options);
var user2 = new Class(options);

"this" . Windows. , Class.

, - Class.prototype, hasOwnProperty for in

0

All Articles