JavaScript 프로토 타입은 Lua의 __index & __newindex와 동등한 것이 있습니까?

StackOverflow https://stackoverflow.com/questions/1642167

  •  10-07-2019
  •  | 
  •  

문제

참조 된 속성/메소드가 존재하지 않을 때 시작되는 JavaScript 객체의 동작을 정의하고 싶습니다. Lua에서는 메타 타블과 __index & __newindex 행동 양식.

--Lua code
o = setmetatable({},{__index=function(self,key)
  print("tried to undefined key",key)
  return nil
end
})

자바 스크립트에 비슷한 것이 있는지 궁금합니다.

내가 달성하려는 것은 이와 같이 작동하는 일반적인 RPC 인터페이스입니다 (유효한 JavaScript가 아님).

function RPC(url)
{
    this.url = url;
}

RPC.prototype.__index=function(methodname) //imagine that prototype.__index exists
{ 
    AJAX.get(this.url+"?call="+ methodname);
}

var proxy = RPC("http://example.com/rpcinterface");
proxy.ServerMethodA(1,2,3);
proxy.ServerMethodB("abc");

그래서 어떻게 할 수 있습니까?

이 작업을 수행 할 수 있습니까?

도움이 되었습니까?

해결책

JavaScript는 SmallTalk (정의되지 않은 메소드를 지원) 또는 LUA와 같은 방식보다 체계와 비슷합니다. 불행히도 귀하의 요청은 제가 아는 한 최선을 다해 뒷받침되지 않습니다.

추가 단계 로이 동작을 모방 할 수 있습니다.

function CAD(object, methodName) // Check and Attach Default
{
    if (!(object[methodName] && typeof object[methodName] == "function") &&
         (object["__index"] && typeof object["__index"] == "function")) {
        object[methodName] = function() { return object.__index(methodName); };
    }
}

그래서 당신의 예가됩니다

function RPC(url)
{
    this.url = url;
}

RPC.prototype.__index=function(methodname) //imagine that prototype.__index exists
{ 
    AJAX.get(this.url+"?call="+ methodname);
}

var proxy = RPC("http://example.com/rpcinterface");
CAD(proxy, "ServerMethodA");
proxy.ServerMethodA(1,2,3);
CAD(proxy, "ServerMethodB");
proxy.ServerMethodB("abc");

더 많은 기능이 CAD에서 구현 될 수 있지만 이는 아이디어를 제공합니다 ... 제가 소개 한 추가 단계를 우회하여 인수가있는 경우 기능을 호출하는 호출 메커니즘으로 사용할 수도 있습니다.

다른 팁

FYI : Firefox는 비표준을 지원합니다 __noSuchMethod__ 확대.

나는 당신이 전달하는 매개 변수로 아무것도하지 않기 때문에 당신의 실제 요구는 예보다 더 복잡하다고 생각합니다. ServerMethodA 그리고 ServerMethodB, 그렇지 않으면 당신은 단지 같은 일을 할 것입니다

function RPC(url)
{
    this.url = url;
}

RPC.prototype.callServerMethod = function(methodname, params)
{ 
    AJAX.get(this.url+"?call="+ methodname);
}

var proxy = RPC("http://example.com/rpcinterface");
proxy.callServerMethod("ServerMethodA", [1,2,3]);
proxy.callServerMethod("ServerMethodB", "abc");

8 년, 8 개월 전에 물었습니다

이제 우리는 '프록시'를 사용할 수 있습니다.

프록시 -JavaScript | MDN

간단한 사용 방법 :

--lua 코드

local o = setmetatable({},{__index=function(self,key)
  print("tried to undefined key",key)
  return nil
end

// JavaScript의 프록시와 함께

let o = new Proxy({}, {
    get: function (target, key, receiver) {
        if (!target.hasOwnProperty(key)){
            console.log("tried to undefined key "+key);
        }
        return Reflect.get(target, key, receiver);
    },
    set: function (target, key, value, receiver) {
        console.log(`set `+ key);
        return Reflect.set(target, key, value, receiver);
    }
})

get : __index

세트 : __newindex

반사 : awget

반사 세트 : 원시 세트

콘솔에서 :

let o= new Proxy({},{
    get: function (target, key, receiver) {
            let ret = Reflect.get(target, key, receiver);
            if (!target.hasOwnProperty(key)){
                console.log("tried to undefined key "+key);
            }
            return ret;
        }
})
>> undefined

o.a
>> VM383:5 tried to undefined key a
>> undefined

o.a = 1
>> 1

o.a
>> 1
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top