JavaScript 프로토 타입을 사용하는 호출 방법
재정의 된 경우 JavaScript의 프로토 타입 메소드에서 기본 메소드를 호출 할 수 있습니까?
MyClass = function(name){
this.name = name;
this.do = function() {
//do somthing
}
};
MyClass.prototype.do = function() {
if (this.name === 'something') {
//do something new
} else {
//CALL BASE METHOD
}
};
정확히 무엇을하려고하는지 이해하지 못했지만 일반적으로 객체 별 동작을 구현하는 것은 다음 라인을 따라 수행됩니다.
function MyClass(name) {
this.name = name;
}
MyClass.prototype.doStuff = function() {
// generic behaviour
}
var myObj = new MyClass('foo');
var myObjSpecial = new MyClass('bar');
myObjSpecial.doStuff = function() {
// do specialised stuff
// how to call the generic implementation:
MyClass.prototype.doStuff.call(this /*, args...*/);
}
이를 수행하는 한 가지 방법은 기본 메소드를 저장 한 다음 대체 메소드에서이를 호출하는 것입니다.
MyClass.prototype._do_base = MyClass.prototype.do;
MyClass.prototype.do = function(){
if (this.name === 'something'){
//do something new
}else{
return this._do_base();
}
};
나는 당신의 모범이 당신의 생각대로 작동하지 않을까 두려워합니다. 이 부분:
this.do = function(){ /*do something*/ };
의 정의를 덮어 씁니다.
MyClass.prototype.do = function(){ /*do something else*/ };
새로 작성된 오브젝트에는 이미 "do"특성이 있으므로 프로토 타입 체인을 찾지 않습니다.
Javascript의 고전적인 상속 형태는 어색하며 파악하기가 어렵습니다. Douglas Crockfords 간단한 상속 패턴을 대신 사용하는 것이 좋습니다. 이처럼 :
function my_class(name) {
return {
name: name,
do: function () { /* do something */ }
};
}
function my_child(name) {
var me = my_class(name);
var base_do = me.do;
me.do = function () {
if (this.name === 'something'){
//do something new
} else {
base_do.call(me);
}
}
return me;
}
var o = my_child("something");
o.do(); // does something new
var u = my_child("something else");
u.do(); // uses base function
제 생각에는 자바 스크립트에서 객체, 생성자 및 상속을 처리하는 훨씬 명확한 방법입니다. Crockfords Javascript : The good parts 에서 더 많은 내용을 읽을 수 있습니다 .
나는이 게시물이 4 년 전이라는 것을 알고 있지만 C # 배경으로 인해 클래스 이름을 지정하지 않고 기본 클래스를 호출하는 방법을 찾고 있었지만 하위 클래스의 속성으로 가져옵니다. 그래서 Christoph의 대답에 대한 나의 유일한 변화 는
이것으로부터:
MyClass.prototype.doStuff.call(this /*, args...*/);
이에:
this.constructor.prototype.doStuff.call(this /*, args...*/);
function NewClass() {
var self = this;
BaseClass.call(self); // Set base class
var baseModify = self.modify; // Get base function
self.modify = function () {
// Override code here
baseModify();
};
}
이와 같은 함수를 정의하면 (OPP 사용)
function Person(){};
Person.prototype.say = function(message){
console.log(message);
}
프로토 타입 함수를 호출하는 두 가지 방법이 있습니다. 1) 인스턴스를 만들고 객체 함수를 호출합니다.
var person = new Person();
person.say('hello!');
그리고 다른 방법은 ... 2) 프로토 타입에서 직접 함수를 호출하는 것입니다.
Person.prototype.say('hello there!');
대안 :
// shape
var shape = function(type){
this.type = type;
}
shape.prototype.display = function(){
console.log(this.type);
}
// circle
var circle = new shape('circle');
// override
circle.display = function(a,b){
// call implementation of the super class
this.__proto__.display.apply(this,arguments);
}
이 솔루션은 Object.getPrototypeOf
TestA
가지고있는 슈퍼 getName
TestB
is a child that overrides getName
but, also has getBothNames
that calls the super
version of getName
as well as the child
version
function TestA() {
this.count = 1;
}
TestA.prototype.constructor = TestA;
TestA.prototype.getName = function ta_gn() {
this.count = 2;
return ' TestA.prototype.getName is called **';
};
function TestB() {
this.idx = 30;
this.count = 10;
}
TestB.prototype = new TestA();
TestB.prototype.constructor = TestB;
TestB.prototype.getName = function tb_gn() {
return ' TestB.prototype.getName is called ** ';
};
TestB.prototype.getBothNames = function tb_gbn() {
return Object.getPrototypeOf(TestB.prototype).getName.call(this) + this.getName() + ' this object is : ' + JSON.stringify(this);
};
var tb = new TestB();
console.log(tb.getBothNames());
If I understand correctly, you want Base functionality to always be performed, while a piece of it should be left to implementations.
You might get helped by the 'template method' design pattern.
Base = function() {}
Base.prototype.do = function() {
// .. prologue code
this.impldo();
// epilogue code
}
// note: no impldo implementation for Base!
derived = new Base();
derived.impldo = function() { /* do derived things here safely */ }
If you know your super class by name, you can do something like this:
function Base() {
}
Base.prototype.foo = function() {
console.log('called foo in Base');
}
function Sub() {
}
Sub.prototype = new Base();
Sub.prototype.foo = function() {
console.log('called foo in Sub');
Base.prototype.foo.call(this);
}
var base = new Base();
base.foo();
var sub = new Sub();
sub.foo();
This will print
called foo in Base
called foo in Sub
called foo in Base
as expected.
Another way with ES5 is to explicitely traverse the prototype chain using Object.getPrototypeOf(this)
const speaker = {
speak: () => console.log('the speaker has spoken')
}
const announcingSpeaker = Object.create(speaker, {
speak: {
value: function() {
console.log('Attention please!')
Object.getPrototypeOf(this).speak()
}
}
})
announcingSpeaker.speak()
No, you would need to give the do function in the constructor and the do function in the prototype different names.
In addition, if you want to override all instances and not just that one special instance, this one might help.
function MyClass() {}
MyClass.prototype.myMethod = function() {
alert( "doing original");
};
MyClass.prototype.myMethod_original = MyClass.prototype.myMethod;
MyClass.prototype.myMethod = function() {
MyClass.prototype.myMethod_original.call( this );
alert( "doing override");
};
myObj = new MyClass();
myObj.myMethod();
result:
doing original
doing override
function MyClass() {}
MyClass.prototype.myMethod = function() {
alert( "doing original");
};
MyClass.prototype.myMethod_original = MyClass.prototype.myMethod;
MyClass.prototype.myMethod = function() {
MyClass.prototype.myMethod_original.call( this );
alert( "doing override");
};
myObj = new MyClass();
myObj.myMethod();
참고URL : https://stackoverflow.com/questions/560829/calling-method-using-javascript-prototype
'development' 카테고리의 다른 글
Express와 hapi는 어떻게 다른가요? (0) | 2020.07.05 |
---|---|
ES6에서 객체를 복제하는 좋은 방법입니까? (0) | 2020.07.05 |
객체의 총 항목 수를 반환하는 가장 좋은 RESTful 방법은 무엇입니까? (0) | 2020.07.05 |
IPA 재 서명 (iPhone) (0) | 2020.07.05 |
Amazon S3 CORS (Cross-Origin Resource Sharing) 및 Firefox 도메인 간 글꼴로드 (0) | 2020.07.05 |