JavaScript : 프로토 타입 방법 오류?
-
18-09-2019 - |
문제
이 코드가있을 때 "testfunc이 정의되지 않은"오류가 발생합니다 ...
/* my_object.js */
"use strict";
function MyObject (param) {
this.param = param;
}
MyObject.prototype.TestFunc = function () {
console.log ('in TestFunc');
}
MyObject.prototype.RealFunc = function () {
// I have tried 3 different ways to call TestFunc:
// 1.
this.TestFunc ();
// 2.
TestFunc ();
// 3. (I didn't really think this would work,
// but thought it was worth a try...)
MyObject.TestFunc ();
}
...이 코드에서 실행됩니다.
/* index.js */
var myObj = new MyObject ('test');
myObj.RealFunc (); // Firebug: "TestFunc is not defined"
해결책
// 1.
this.TestFunc ();
괜찮아. 다른 통화가 제거되면서 작동합니다.
(글쎄, 그것은 당신이 껍질을 벗기지 않는 한 RealFunc
소유자로부터 var method= myObj.RealFunc; method();
또는 이벤트 핸들러 또는 시간 초과를 통해. 이 경우 this
RealFunc에서는 myObject 인스턴스가 아니며 폐쇄를 보거나 Function.bind
작동하기 위해.)
// 2.
TestFunc ();
아니요, TestFunc은 로컬 또는 글로벌 범위에서 변수로 정의되지 않습니다. 이렇게하면 Firebug에서 얻은 오류가 발생합니다.
// 3. (I didn't really think this would work,
// but thought it was worth a try...)
MyObject.TestFunc ();
아니, 당신이 옳았습니다. :-) 그럴 것이다 MyObject.prototype.TestFunc.call(this)
, 명시 적으로 완료되었습니다.
JavaScript는 프로토 타입과 같이 내장 객체의 표준 생성자 기능에 동일한 방법 중 일부를 넣어 문제를 혼동합니다 (예 : String.split
실제로 만 존재합니다 String.prototype.split
해야 한다). 그러나 그것은 당신이 명시 적으로 말하지 않는 한 자신의 물건에 일어나지 않습니다. MyObject.TextFunc= MyObject.prototype.TextFunc
.
다른 팁
변형 1이 정확해 보입니다. Executejs에서 귀하의 코드를 시도하고 2. 및 3을 건너 뛰었습니다. console.log
그리고 그것을 변경했습니다 alert
). TestFunc
내부에 호출됩니다 RealFunc
.
제거하면 어떻게됩니다 "use strict";
?