简体   繁体   English

这个”是指窗口对象

[英]this" refers to window object

In the BusMonitor object, "this" refers to window object thats why "name" property become global for entire script when I call BaseFunction.call(this) on BusMonitor object. 在BusMonitor对象中,“ this”是指窗口对象,这就是为什么当我在BusMonitor对象上调用BaseFunction.call(this)时,“ name”属性对于整个脚本都是全局的。 I just want the BaseFunction's properties only available to BusMonitor object. 我只希望BaseFunction的属性仅对BusMonitor对象可用。 How to do that ? 怎么做 ?

function BaseFunction() {

    this.name = "test";

}

var BusMonitor = function () {

    BaseFunction.call(this);

    return {
        init: function () {
        }
    }

}();

I can do it by the way below but I dont want to create object like this. 我可以通过下面的方式做到这一点,但我不想创建这样的对象。

function BusMonitor () {

    BaseFunction.call(this);

    return {
        init: function () {

        }
    }

};

var busMonitor = new BusMonitor();
busMonitor.init();

You can define a localScope in BusMonitor to hold name value, like this: 您可以在BusMonitor中定义一个localScope来保存名称值,如下所示:

function BaseFunction() {
    this.name = "test";
}

var BusMonitor = function () {
    var localScope = {};
    BaseFunction.call(localScope);
    console.log("local name:" + localScope.name);
    return {
        init: function () {
        }
    }

}();
console.log("global name: " + name);

You can, if it's possible of course, create object first and then pass it to BaseFunction 如果可以的话,您可以先创建对象,然后将其传递给BaseFunction

function BaseFunction() {
    this.name = "test";
}

var BusMonitor = function () {
    var obj = {
        init: function () { }
    };

    BaseFunction.call(obj);

    return obj;
}();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM