자바 스크립트 객체에 메소드 추가
내가 Foo
물건 이 있다고 가정
bar()
메서드 를 추가하여이 개체를 확장 하고의 향후 인스턴스 Foo
에이 메서드가 있는지 확인하려면 어떻게해야합니까?
Foo의 프로토 타입에 추가해야합니다.
function Foo(){}
Foo.prototype.bar = function(){}
var x = new Foo()
x.bar()
이것은 모두 당신이 만드는 Foo
방법과 사용하려는 방법 에 달려 있습니다 .bar()
.
첫째, 객체에 생성자 함수를 사용하고 있습니까?
var myFoo = new Foo();
그렇다면 다음과 같이를 사용하여 Foo
함수의 prototype
속성을 확장 할 수 있습니다 .bar
.
function Foo () { /*...*/ }
Foo.prototype.bar = function () { /*...*/ };
var myFoo = new Foo();
myFoo.bar();
이러한 방식으로 Foo
이제의 각 인스턴스는 의 SAME 인스턴스에 액세스 할 수 .bar
있습니다.
재치 :에 .bar
대한 전체 액세스 권한을 this
갖지만 생성자 함수 내에서 액세스 할 variables
수는 없습니다 .
function Foo () { var secret = 38; this.name = "Bob"; }
Foo.prototype.bar = function () { console.log(secret); };
Foo.prototype.otherFunc = function () { console.log(this.name); };
var myFoo = new Foo();
myFoo.otherFunc(); // "Bob";
myFoo.bar(); // error -- `secret` is undefined...
// ...or a value of `secret` in a higher/global scope
다른 방법 으로 해당 객체의 속성으로 생성 된 모든 객체 (아님 this
) 를 반환하는 함수를 정의 할 수 있습니다 .bar
.
function giveMeObj () {
var private = 42,
privateBar = function () { console.log(private); },
public_interface = {
bar : privateBar
};
return public_interface;
}
var myObj = giveMeObj();
myObj.bar(); // 42
이러한 방식으로 새로운 객체를 생성하는 기능이 있습니다.
이러한 각 개체에는 해당 개체에 대해 .bar
생성 된 함수가 있습니다.
각 .bar
기능은 소위을 통해 액세스,이 폐쇄 자신의 특정 개체를 반환하는 함수 내에서 "개인"변수를.
각 함수 .bar
는 여전히에 액세스 할 수 this
있으며 this
, 함수를 호출 할 때 myObj.bar();
항상 myObj
( public_interface
, 내 예에서는 Foo
)를 참조합니다 .
이 형식의 단점은 이러한 개체를 수백만 개 만들려는 경우에도 수백만 개의 복사본이 .bar
메모리에 저장된다는 것입니다.
생성자 함수 내에서이 작업을 수행 할 수도 있습니다. 생성자 this.bar = function () {};
내부 에서 설정 하면 다시 한 번, 생성자에서 개인 변수에 대한 클로저 액세스가 가능하고 단점은 메모리 요구 사항이 증가하는 것입니다.
첫 번째 질문은 그래서 :
당신이 당신의 방법은 대상 (를 통해 자체를 통해 액세스 할 수 없습니다 / 수정 "개인"데이터를 읽을 수있는 액세스있을 것으로 예상합니까 this
또는 myObj.X
)?
두 번째 질문은 다음과 같습니다. 메모리가 큰 관심사가 될 수 있도록 이러한 개체를 충분히 만들고 있습니까? 공유 할 개체를 제공하는 대신 각각의 개인 기능을 제공한다면?
For example, if you gave every triangle and every texture their own .draw
function in a high-end 3D game, that might be overkill, and it would likely affect framerate in such a delicate system...
If, however, you're looking to create 5 scrollbars per page, and you want each one to be able to set its position and keep track of if it's being dragged, without letting every other application have access to read/set those same things, then there's really no reason to be scared that 5 extra functions are going to kill your app, assuming that it might already be 10,000 lines long (or more).
There are many ways to create re-usable objects like this in JavaScript. Mozilla have a nice introduction here:
The following will work in your example:
function Foo(){
this.bar = function (){
alert("Hello World!");
}
}
myFoo = new Foo();
myFoo.bar(); // Hello World
You can make bar a function making it a method.
Foo.bar = function(passvariable){ };
As a property it would just be assigned a string, data type or boolean
Foo.bar = "a place";
참고URL : https://stackoverflow.com/questions/13521833/javascript-add-method-to-object
'Development Tip' 카테고리의 다른 글
Bootstrap 모달 창을 PartialView로 사용 (0) | 2020.11.23 |
---|---|
선택자에 변수를 사용할 수 있습니까? (0) | 2020.11.23 |
Java에서 db 리스너를 구현하는 방법 (0) | 2020.11.21 |
Atom의 시작 화면을 제거하는 방법 (0) | 2020.11.21 |
MVC의 대안 (0) | 2020.11.21 |