객체 대 클래스 대 기능
JavaScript 객체, 클래스 및 함수의 차이점은 무엇입니까? 클래스와 함수가 객체의 유형이라고 생각하는 것이 맞습니까?
클래스와 함수의 차이점은 무엇입니까? 아니면 그것들은 정말로 똑같은 것일까 요? 사용 방법에 따라 용어가 바뀌는 것일까 요?
function func() { alert('foo'); } // a function
func(); // call the function - alerts 'foo'
var func2 = function () { alert('hello'); } // acts the same way as 'func' surely?
func2(); // alerts 'hello'
var Class = function() { alert('bar'); }; // a class
var c = new Class(); // an istance of a class - alerts 'bar'
물론, 클래스에는 메서드와 속성이 있으며 인스턴스화 될 수 있습니다.하지만 이전 함수로도 동일한 작업을 수행 할 수 있습니다.
이미 알고 계시 겠지만 JavaScript에는 클래스가 없습니다. 대신 JavaScript의 함수는 함수 호출 앞에 new
키워드를 사용하여 생성자처럼 작동하도록 만들 수 있습니다 . 이것을 생성자 패턴이라고 합니다.
JavaScript에서는 기본 데이터 유형 (부울, 숫자 및 문자열)을 제외한 모든 것이 객체 undefined
입니다. 반면 null
에 처음에는 그렇지 않다고 생각할지라도 실제로는 객체 참조입니다. 이것이 typeof null
반환 이유 "object"
입니다.
JavaScript의 함수는 Lua의 함수와 유사합니다 (즉, 호출 가능한 객체). 따라서 객체 대신 함수를 사용할 수 있습니다. 마찬가지로 배열도 JavaScript의 객체입니다. 반면에 객체는 연관 배열로 생각할 수 있습니다.
그러나 가장 중요한 점은 JavaScript가 프로토 타입 객체 지향 언어이기 때문에 JavaScript에는 클래스가 없다는 것입니다. 즉, JavaScript의 객체는 다른 객체에서 직접 상속됩니다. 따라서 우리는 수업이 필요하지 않습니다. 우리에게 필요한 것은 객체를 만들고 확장하는 방법입니다.
JavaScript의 프로토 타입 상속에 대해 자세히 알아 보려면 다음 스레드를 읽어보십시오. 클래식보다 프로토 타입 상속의 이점?
2015 업데이트
자바 스크립트에는 이전 브라우저에서 사용되지 않는 클래스가 있습니다.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
생성자, 확장 기능 등이 있습니다.
class Cat {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Lion extends Cat {
speak() {
super.speak();
console.log(this.name + ' roars.');
}
}
JS 수업 :
function Animal(){
// Private property
var alive=true;
// Private method
function fight(){ //... }
// Public method which can access private variables
this.isAlive = function() { return alive; }
// Public property
this.name = "Joe";
}
// Public method
Animal.prototype.play = function() { alert("Bow wow!"); }
// .. and so on
이제 객체를 만들 때
var obj = new Animal();
다른 언어의 개체에서와 마찬가지로이 개체의 모든 것을 기대할 수 있습니다. 그것을 달성하려는 노력은 조금 달랐습니다. 또한 JS 에서 상속을 살펴 봐야합니다 .
귀하의 질문을 다시 받으면 다음과 같이 다시 표현하겠습니다.
Class : A representation of a set with common properties.
object : One from the set with the same properties.
var Class = function() {alert('bar');}; // A set of function which alert 'bar'
var object = new Class(); // One of the functions who alert's 'bar'.
JavaScript does not have classes, and functions are actually objects in JavaScript (first-class citizens). The only difference that function objects have is that they are callable.
function func() { alert('foo'); } // a function
- Correct
func(); // call the function - alerts 'foo'
- Correct
var func2 = function () { alert('foo'); } // same as 'func' surely?
- Nope, func2
is a different object, that apparently does the same thing when called.
var Class = function() { alert('bar'); };
- It's a function with no name stored in variable Class
.
var c = new Class();
- Calls function stored in Class
supplying new empty object as this
and returning that object. Functions called as new functionA()
are expected to work as constructors and prepare a newly created object (this
). In your case - constructor does nothing with the object and just alerts bar
.
There are no classes in javascript. But, there are ways to make a function to behave like a class in other languages.
A very good explanation is given here 3 way to define a class in js
Also, found a very good reference for OOP in Javascript
Object is the base type in JavaScript i.e. all the user defined data types inherits from Object in one way or another. So if you define a function or a class [note as of now JS doesn't support class construct, but its proposed in ECMAScript version 6], it will implicitly inherit from Object type.
Classes are really used for encapsulating logical functions and properties into one type / entity and you can 'new' it up using constructor syntax. So if you define a 'Customer' class, you can instantiate it multiple times and each instance / object can have different values. They can even share the values if you define class level value using prototype.
JS는 현재 클래스 구성을 지원하지 않기 때문에 함수는 다른 함수 나 유형에 대한 컨테이너뿐만 아니라 개별 메서드로도 작동 할 수 있습니다.
ECMAScript 6을 사용하면 C #, Java 등과 같은 다른 언어에서 사용하는 것과 유사한 구조를 명확하게 구분할 수 있기를 바랍니다.
또한 ES6에서 다음과 같은 수업을받습니다.
//class
class Cat {
//constructor
constructor() {
this.name = 'Snowball';
}
//method
meow() {
console.log('Hello, nyah! My name is ' + this.name + ' nyah!~');
}
};
참조 URL : https://stackoverflow.com/questions/17525450/object-vs-class-vs-function
'your programing' 카테고리의 다른 글
VS 2012에서 MVC4 프로젝트를 만들 때 NuGet 오류 (0) | 2020.12.29 |
---|---|
jQuery UI 대화 상자-인스턴스 메서드에 의해 존재하는지 확인 (0) | 2020.12.29 |
isnan ()에 해당하는 Swift는 무엇입니까? (0) | 2020.12.29 |
UITableView-Swift로 registerClass (0) | 2020.12.29 |
자바 스크립트에서 CSS 변수에 액세스 (0) | 2020.12.29 |