JavaScript의 클래스 대 스태틱 메서드
효과가 있을 거란 걸 알아요
function Foo() {};
Foo.prototype.talk = function () {
alert('hello~\n');
};
var a = new Foo;
a.talk(); // 'hello~\n'
하지만 내가 전화하려면
Foo.talk() // this will not work
Foo.prototype.talk() // this works correctly
해서 만드는 이 몇 가지 있어요.Foo.talk 일하다
Foo.__proto__ = Foo.prototypeFoo.talk = Foo.prototype.talk
다른 방법이 있나요?그렇게 하는 것이 옳은지 모르겠다.JavaScript 코드에서 클래스 메서드 또는 스태틱 메서드를 사용하고 있습니까?
먼저 JavaScript는 주로 클래스 기반1 언어가 아닌 프로토타입 언어임을 기억하십시오. Foo클래스가 아니라 기능, 객체입니다.이 함수에서 오브젝트를 인스턴스화하려면new표준 OOP 언어로 클래스와 유사한 것을 만들 수 있는 키워드입니다.
해 좋겠다__proto__ 크로스 지원이 에 대신 해야 하는지 하는 데 초점을 있습니다.prototype
함수에서2 생성된 객체의 인스턴스가 있고 해당 멤버 중 하나(메서드, 속성, 속성, 상수 등)에 액세스하는 경우, 접근은 (a) 해당 멤버를 찾거나 (b) 다른 프로토타입을 찾지 않을 때까지 프로토타입 계층을 따라 흐릅니다.
계층은 호출된 개체에서 시작된 다음 프로토타입 개체를 검색합니다.됩니다.undefined이 반환됩니다.
예를 들어 다음과 같습니다.
foo = {bar: 'baz'};
console.log(foo.bar); // logs "baz"
foo = {};
console.log(foo.bar); // logs undefined
function Foo(){}
Foo.prototype = {bar: 'baz'};
f = new Foo();
console.log(f.bar);
// logs "baz" because the object f doesn't have an attribute "bar"
// so it checks the prototype
f.bar = 'buzz';
console.log( f.bar ); // logs "buzz" because f has an attribute "bar" set
제가 보기엔 적어도 이 "기본" 부분들은 어느 정도 이해하신 것 같지만, 만약을 위해 분명히 말씀드려야겠습니다.
JavaScript에서는 모든 것이 객체입니다3.
모든 것은 물건이다.
function Foo(){}는 단순히 함수를 하는 것이 오브젝트는, 「」를 사용해 할 수 .Foo.
접속할 수 .Foo과 ' ' ' ' 。Foo.prototype.
또한 더 많은 기능을 설정할 수 있습니다.Foo:
Foo.talk = function () {
alert('hello world!');
};
이 새로운 기능은 다음을 사용하여 액세스할 수 있습니다.
Foo.talk();
지금쯤 함수 객체의 함수와 정적 메서드의 유사성이 눈에 띄었기를 바랍니다.
f = new Foo(); 인스턴스시 " " " " " 입니다.Foo.prototype.bar = function(){...}.또, 「」는 「공유 메서드」를 정의하고 있습니다.Foo.baz = function(){...}클래스의 퍼블릭스태틱 메서드를 정의합니다.
ECMAScript 2015는 이러한 종류의 선언을 위해 다양한 통사당을 도입하여 구현하기 쉽고 읽기 쉬웠다.따라서 위의 예는 다음과 같이 기술할 수 있습니다.
class Foo {
bar() {...}
static baz() {...}
}
에, 「」가 가능하게 됩니다.bar★★★★
const f = new Foo()
f.bar()
★★★★★★★★★★★★★★★★★」baz★★★★
Foo.baz()
1: ECMAScript 5 사양에서는 "미래 예약어"였지만 ES6에서는 다음 명령어를 사용하여 클래스를 정의할 수 있는 기능이 도입되었습니다.class키워드를 지정합니다.
2: 기본적으로는 컨스트럭터에 의해 생성된 클래스 인스턴스입니다만, 오해하고 싶지 않은 미묘한 차이가 많이 있습니다.
3: 기본 값: 다음을 포함합니다.undefined,null 숫자,으로는 낮은 구현이기 않습니다 , 부안, 부안, 부안, 부안, 부안 - 부안 - 부안 - 부안 - 부안 - 부안 - 부안 - 부안 - 부안 - 부안 - 부안 - 부안 - 부안 - 부안 - 부안 - 부안입니다.부울, 숫자 및 문자열은 여전히 원형 체인과 마치 물체인 것처럼 상호 작용하므로, 이 답변의 목적상, 그것들이 완전히는 아니지만 "객체"로 간주하는 것이 더 쉽습니다.
다음과 같이 달성할 수 있습니다.
function Foo() {};
Foo.talk = function() { alert('I am talking.'); };
이제 다음과 같이 "talk" 기능을 호출할 수 있습니다.
Foo.talk();
JavaScript에서는 함수도 객체이기 때문에 이 작업을 수행할 수 있습니다.
인스턴스에서 스태틱메서드를 호출합니다.
function Clazz() {};
Clazz.staticMethod = function() {
alert('STATIC!!!');
};
Clazz.prototype.func = function() {
this.constructor.staticMethod();
}
var obj = new Clazz();
obj.func(); // <- Alert's "STATIC!!!"
간단한 Javascript 클래스 프로젝트: https://github.com/reduardo7/sjsClass
다음은 Javascript가 정적/인스턴스 변수 및 메서드에서 어떻게 작동하는지 보여주는 좋은 예입니다.
function Animal(name) {
Animal.count = Animal.count+1||1;// static variables, use function name "Animal"
this.name = name; //instance variable, using "this"
}
Animal.showCount = function () {//static method
alert(Animal.count)
}
Animal.prototype.showName=function(){//instance method
alert(this.name);
}
var mouse = new Animal("Mickey");
var elephant = new Animal("Haddoop");
Animal.showCount(); // static method, count=2
mouse.showName();//instance method, alert "Mickey"
mouse.showCount();//Error!! mouse.showCount is not a function, which is different from Java
, 재, 음, 음, 음, 음 등으로 할 수 .class ★★★★★★★★★★★★★★★★★」static
'use strict'
class Foo {
static talk() {
console.log('talk')
};
speak() {
console.log('speak')
};
};
줄 것이다
var a = new Foo();
Foo.talk(); // 'talk'
a.talk(); // err 'is not a function'
a.speak(); // 'speak'
Foo.speak(); // err 'is not a function'
네임스페이스를 사용합니다.
var Foo = {
element: document.getElementById("id-here"),
Talk: function(message) {
alert("talking..." + message);
},
ChangeElement: function() {
this.element.style.color = "red";
}
};
사용방법:
Foo.Talk("Testing");
또는
Foo.ChangeElement();
는 ES6를 하게 되었습니다.class&static : "Charm" : "Charm" :
class Foo {
constructor() {}
talk() {
console.log("i am not static");
}
static saying() {
console.log(this.speech);
}
static get speech() {
return "i am static method";
}
}
ES5에서 정적 메서드를 작성해야 하는 경우 다음과 같은 훌륭한 튜토리얼을 찾았습니다.
//Constructor
var Person = function (name, age){
//private properties
var priv = {};
//Public properties
this.name = name;
this.age = age;
//Public methods
this.sayHi = function(){
alert('hello');
}
}
// A static method; this method only
// exists on the class and doesn't exist
// on child objects
Person.sayName = function() {
alert("I am a Person object ;)");
};
참조 @http://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/
추가 사항만 있습니다.클래스 ES6를 사용하여 정적 메서드를 만들 때..Javacscript 엔진은 디스크립터 속성을 구식 "static" 메서드와는 다른 릴 비트를 설정합니다.
function Car() {
}
Car.brand = function() {
console.log('Honda');
}
console.log(
Object.getOwnPropertyDescriptors(Car)
);
brand()의 내부 애트리뷰트(프로퍼티)를 다음과 같이 설정합니다.
..
brand: [object Object] {
configurable: true,
enumerable: true,
value: ..
writable: true
}
..
비교해서
class Car2 {
static brand() {
console.log('Honda');
}
}
console.log(
Object.getOwnPropertyDescriptors(Car2)
);
brand()의 내부 애트리뷰트를 로 설정합니다.
..
brand: [object Object] {
configurable: true,
enumerable: false,
value:..
writable: true
}
..
ES6의 정적 메서드에 대해 열거 가능이 false로 설정되어 있는지 확인합니다.
즉, for-in 루프를 사용하여 오브젝트를 체크할 수 없습니다.
for (let prop in Car) {
console.log(prop); // brand
}
for (let prop in Car2) {
console.log(prop); // nothing here
}
ES6의 static 메서드는 static 메서드가 아직 쓰기 가능하기 때문에 기술자가 쓰기 가능함을 제외하고 다른 클래스의 개인 속성(이름, 길이, 생성자)과 동일하게 취급됩니다. { writable: true },로 할 도 있습니다.
Car2.brand = function() {
console.log('Toyota');
};
console.log(
Car2.brand() // is now changed to toyota
);
「 」에를 걸려고 ,Foo.talk JS의 talk통해.__proto__물론 찾을 수 없습니다.
Foo.__proto__이Function.prototype.
스태틱 메서드콜은 클래스에서 직접 발신되며 클래스의 인스턴스에서는 호출할 수 없습니다.유틸리티 함수를 작성하기 위해 정적 메서드가 자주 사용됩니다.
명료한 설명
Foo는 클래스에 바인딩해야 합니다.그러면 새 인스턴스를 만들 때 myNewInstance.foo() 클래스를 Import하면 static 메서드를 호출할 수 있습니다.
그런 상황에 직면했을 때, 저는 다음과 같은 일을 해왔습니다.
Logger = {
info: function (message, tag) {
var fullMessage = '';
fullMessage = this._getFormatedMessage(message, tag);
if (loggerEnabled) {
console.log(fullMessage);
}
},
warning: function (message, tag) {
var fullMessage = '';
fullMessage = this._getFormatedMessage(message, tag);
if (loggerEnabled) {
console.warn(fullMessage);`enter code here`
}
},
_getFormatedMessage: function () {}
};
그래서 나는 이제 info method를 부를 수 있다.Logger.info("my Msg", "Tag");
당신의 경우, 당신이 원한다면Foo.talk():
function Foo() {};
// But use Foo.talk would be inefficient
Foo.talk = function () {
alert('hello~\n');
};
Foo.talk(); // 'hello~\n'
이렇게 하는 prototype더 좋아요.
다른 방법으로 My way는 스태틱클래스로 정의됩니다.
var Foo = new function() {
this.talk = function () {
alert('hello~\n');
};
};
Foo.talk(); // 'hello~\n'
는 사용하지 됩니다.prototype정적 사용으로 한 번만 구성되기 때문입니다.
https://github.com/yidas/js-design-patterns/tree/master/class
Javascript는 실제 클래스는 없으며 프로토타입 체인을 통해 다른 객체로부터 객체를 '상속'하는 프로토타입 상속 시스템을 사용합니다.이는 코드 자체를 통해 가장 잘 설명됩니다.
function Foo() {};
// creates a new function object
Foo.prototype.talk = function () {
console.log('hello~\n');
};
// put a new function (object) on the prototype (object) of the Foo function object
var a = new Foo;
// When foo is created using the new keyword it automatically has a reference
// to the prototype property of the Foo function
// We can show this with the following code
console.log(Object.getPrototypeOf(a) === Foo.prototype);
a.talk(); // 'hello~\n'
// When the talk method is invoked it will first look on the object a for the talk method,
// when this is not present it will look on the prototype of a (i.e. Foo.prototype)
// When you want to call
// Foo.talk();
// this will not work because you haven't put the talk() property on the Foo
// function object. Rather it is located on the prototype property of Foo.
// We could make it work like this:
Foo.sayhi = function () {
console.log('hello there');
};
Foo.sayhi();
// This works now. However it will not be present on the prototype chain
// of objects we create out of Foo
함수 또는 클래스 객체와 인스턴스(instance)에 메서드와 속성을 구현하는 방법은 다음과 같습니다.
- 클래스(또는 함수) 자체:
Foo.method()★★★★★★★★★★★★★★★★★」Foo.prop - 시제품:
Foo.prototype.method()★★★★★★★★★★★★★★★★★」Foo.prototype.prop시{method:function(){...}, prop:...}따라서 foo 객체는 Foo.protype 객체의 복사본을 프로토타입으로 받습니다. - 인스턴스 자체: 메서드 또는 속성이 개체 자체에 추가됩니다.
foo={method:function(){...}, prop:...}
this키워드는 컨텍스트에 따라 다르게 표현하고 동작합니다.방법에서는 Function: Function: Function: Function: Function: Function: Function: Function: Function: Function: Function: Function: Function: Function: Function: Function: Function: Function: Function:는입니다).class Foo {} let Foo = new Function({})
ECMAScript 2015는 오늘날 잘 구현되어 있는 것처럼 보이지만 클래스(정적) 메서드와 속성, 인스턴스(instance) 메서드와 속성 및 자체 메서드와 속성 간의 차이를 보다 명확하게 확인할 수 있습니다.따라서 이름이 같지만 서로 다른 개체에 적용되기 때문에 다른 세 가지 메서드 또는 속성을 만들 수 있습니다.this메소드에서 키워드는 클래스 오브젝트 자체와 인스턴스 오브젝트에 각각 프로토타입 또는 그 자체에서 적용됩니다.
class Foo {
constructor(){super();}
static prop = "I am static" // see 1.
static method(str) {alert("static method"+str+" :"+this.prop)} // see 1.
prop="I am of an instance"; // see 2.
method(str) {alert("instance method"+str+" : "+this.prop)} // see 2.
}
var foo= new Foo();
foo.prop = "I am of own"; // see 3.
foo.func = function(str){alert("own method" + str + this.prop)} // see 3.
언급URL : https://stackoverflow.com/questions/7694501/class-vs-static-method-in-javascript
'programing' 카테고리의 다른 글
| 넷빈을 실행하는 Java 플랫폼 변경 (0) | 2022.11.30 |
|---|---|
| 오브젝트의 속성을 루프하는 빌트인 방법이 있습니까? (0) | 2022.11.30 |
| JavaScript의 child Nodes와 child Nodes의 차이점은 무엇입니까? (0) | 2022.11.20 |
| MariaDB/MySQL 쿼리는 대소문자를 구분합니까? (0) | 2022.11.20 |
| 홀수 업데이트와 Java 업데이트의 차이점은 무엇입니까? (0) | 2022.11.20 |