最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript - how to use "self" from current JS Class - Stack Overflow

programmeradmin3浏览0评论

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 of 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 in self that I wish to use in each class. The self.name will be undefined because self is a [Window object].


Question: how to modify my code to use self inside all functions in class instances? The self is needed to not drop context if the function will be called from external context.

Expected result (I mean that code above should be executed as 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();

The goal of my experiment is to use self that always is reference to current object. Because sometimes when we use calls like this $.get('...', function () { console.log(this); }) - this is set to function local scope. But I wish to use self (magic property) that always be a reference to object of current class (scope of current 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 of 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 in self that I wish to use in each class. The self.name will be undefined because self is a [Window object].


Question: how to modify my code to use self inside all functions in class instances? The self is needed to not drop context if the function will be called from external context.

Expected result (I mean that code above should be executed as 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();

The goal of my experiment is to use self that always is reference to current object. Because sometimes when we use calls like this $.get('...', function () { console.log(this); }) - this is set to function local scope. But I wish to use self (magic property) that always be a reference to object of current class (scope of current class).

Share Improve this question edited Nov 25, 2014 at 14:50 Anton Danylchenko asked Nov 17, 2014 at 18:58 Anton DanylchenkoAnton Danylchenko 2,3581 gold badge26 silver badges25 bronze badges 9
  • 2 how about name it something else? I usually use me = this; – forgivenson Commented Nov 17, 2014 at 19:01
  • 1 Class doesn't return anything. What do you expect User to be? Either way, in your example self is a local variable and doesn't conflict with the global self variable. Please provide a better explanation of your problem or update your code to better demonstrate the issue. – Felix Kling Commented Nov 17, 2014 at 19:06
  • You probably want something like this: jsfiddle/y7n0ow5t. Since User is a constructor function, you want Class to return a function. – dfsq Commented Nov 17, 2014 at 19:14
  • @FelixKling you are right, I missed new statement. I corrected my code. – Anton Danylchenko Commented Nov 25, 2014 at 11:36
  • 1 This question should be closed as primarily opinion based. What the OP wants to do makes no sense, and there seem to be multiple opinions on how to solve the problem. – Aadit M Shah Commented Nov 25, 2014 at 15:16
 |  Show 4 more ments

2 Answers 2

Reset to default 5

So I finally figured out that you are talking about the self variable in the sayHello method that is giving you problems.

You need to google JavaScript scope this tutorial - it's not the most intuitive concept, but once you get it, everything will make sense.

In the mean time, it's worth pointing out that self is not a reserved word in JavaScript and doesn't do anything special, but this is.

So what you want, is something like this:

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();

The keyword new in front of the Class() function causes it to be executed as a constructor function meaning that, inside of the constructor function this will reference it's own scope.

Also, because the property sayHello is a function to be executed inside the scope that you created, you can use this.name - as this will refer to the scope that you created when you instantiated a new Class.

And just because this scope thing is no doubt confusing (don't worry, it probably will be for a while) - if you haven't created a scope (by using a constructor or object literal) you're working inside of the global scope which, in the case of the browser, is the Window object.

That's because you never created an object:

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

"this" refers to the object owner of the current function. In this case would be windows object. At least you construct an object from the function Class.

If you want to avoid someone overwrite a property of Class.prototype is necessary to use hasOwnProperty in your for in

发布评论

评论列表(0)

  1. 暂无评论