2017-11-15 30 views
1

인스턴스를 생성하는 생성자를 가질 수는 있지만 호출 할 때 특정 함수를 실행할 수 있습니까?자바 스크립트 : 함수와 같은 객체 호출

var Foo = function(){ 
    this.bar= "some variable"; 

    this.invokeFunction = function(){ 
     return this.bar; 
    } 
    return .... // what to do here 
}; 

var foo = new Foo(); 

return foo;  // return the instance of Foo: { bar: "some variable" } 
return foo.bar; // returns "some variable" 
return foo() ; // returns "some variable" 
+0

합니다. 'foo()'는 함수가 아니기 때문에 에러를 던질 것이다. –

+0

'new'의 유무에 관계없이 다르게 동작하는 함수를 요구하고 있습니까? –

답변

1

당신은 이런 식으로 가짜 수 있습니다. Foo는 자신의 프로토 타입을 가리키는 __proto__ 함수를 반환합니다. 반환 된 함수는 호출입니다 Foo의 인스턴스와 인스턴스 속성에 액세스 할 수 있습니다 : 당신은 아무것도 반환 할 필요가 없습니다

var Foo = function(){ 
 
    function inner(){ 
 
     console.log("called") 
 
     return "returned" 
 
    } 
 

 
    inner.__proto__ = Foo.prototype 
 
    inner.bar= "some variable"; 
 
    return inner 
 
}; 
 

 
Foo.prototype.someFn = function(){ 
 
    console.log("called prototype function") 
 
    return this.bar 
 
} 
 

 
var foo = new Foo(); 
 

 
console.log(foo instanceof Foo) // it's an instance of Foo 
 
console.log(foo.bar) // still has access to instance variables 
 
console.log(foo()) // callable! 
 
console.log(foo.someFn()) // prototype function with `this`

0

클래스 함수에서 원하는 것을 반환하는 함수를 반환하십시오. 그래서 이런 식으로 :

var Foo = function(){ 
    this.bar= "some variable"; 

    this.invokeFunction = function(){ 
     return this.bar; 
    } 
    return this.invokeFunction.bind(this); 
}; 
+0

만약 작동한다면, 나는 대답을 받아 들일 수 있으면 좋겠다. – wilsonhobbs

+1

이것은 실제로 작동하지 않는다 :'var f = new Foo(); console.log (f.bar)'---> 정의되지 않았습니다. –