이것은 this
이 javascript의 박스 범위 내에서 작동하는 방식과 관련이 있습니다.
예 :
var obj = {
firstname: "rahul",
lastname: "arora"
getName: function(){
console.log(this);//will output the object as this here points to the object it is defined under
}
};
obj.getName();
방법 자바 스크립트 작품이다
var obj = {
firstname: "rahul",
lastname: "arora"
getName: function(){
function getFullName(){
console.log(this);//this refers to the window and not to the object this time
}
getFullName();
}
};
obj.getName();
반면. 조금 이상하지만이 방법이 설계되었습니다. 당신이 사용할 수있는 객체의 인스턴스를 만들기 위해 생성자 함수를 호출하지만 AngularJS와 서비스는 서비스를 호출 할 때
, 당신이하고있는 아무것도 동일한 개념을 적용
.
사용하는 모든 메소드는 사용자가 사용하는 컨트롤러에 전달 된 객체 인스턴스에 연결됩니다.
이제 해당 서비스의 바로 아래에 있지 않은 개체 내부에 함수가 정의되어있는 경우 위에 설명 된 개념 때문에 올바르게 작동하지 않습니다.
따라서이 값을 함수 내에서 사용하려면 변수의 값을이 변수에 저장해야합니다. 내 대답은 당신의 의심을 지 웁니다 경우
var self = this;
this.init = function() {
self.initFolder()
/*since the function is called from inside a function which is inside an object,
this will not point to that instance of the object in this scenario.
Therefore, you have to store the value of this in a variable to make sure you use that inside this function to make it work properly.*/
...
}
this.initFolder = function() {
// the code inside does not mention "this"
...
}
확인하십시오 :
특정 경우당신은 같은 일을 할 수 있습니다 –