在Javascript中限制main对象对其属性的属性的访问

Restrict access of the main obj to the properties of its properties in Javascript

本文关键字:属性 访问 对象 main Javascript      更新时间:2023-09-26

好的,我正在用javascript创建一个链接方法,我试图存档主对象或类可以访问4个属性,这些属性是函数和属性必须访问主对象不能访问的一些函数。

这里有一个例子:

var Main = function(){
return {
 property1:function(){
return this;
},
property2:function(){
return this;    
},
etc:function(){
    return this;
}...
}
}

像这样执行:

  Main().property1().property2().etc();

Main可以访问它的属性,但是Main不能访问这些属性,这些属性是Main的属性。更简单的方法:just the properties of Main must have access, not Main .

下面是一个例子:

Main().property().innerProperty1().innerProperty2().etc()//cool, property1 can access to innerProperty 1 and 2 and etc()

但是如果我想这样做:

Main().innerProperty() // ERROR, Main does not have acccess to innerProperty()

这在javascript中可能吗?记住必须是可链接的

我仍然不太确定你在问什么,但这是我想到的。我做了两个JS类来演示你所说的。

function Owner(name) {
    this.Name = name;
    this.ChangeName = function (newName) {
        this.Name = newName;
        return this;
    };
}

function Car(make, model, owner) {
    this.Make = make;
    this.Model = model;
    this.Owner = owner;
    this.UpdateMake = function (newMake) {
        this.Make = newMake;
        return this;
    };
    this.UpdateModel = function (newModel) {
        this.Model = newModel;
        return this;
    };
    this.UpdateOwner = function (newOwner) {
        this.Owner = newOwner;
        return this;
    };
}

小提琴在这里:http://jsfiddle.net/whytheday/zz45L/18/

Car将不能访问Owner的名字,除非它先通过Owner。