JavaScript 객체의 컨스트럭터
JavaScript 클래스/오브젝트에 컨스트럭터를 사용할 수 있습니까?어떻게 작성됩니까?
프로토타입 사용:
function Box(color) // Constructor
{
this.color = color;
}
Box.prototype.getColor = function()
{
return this.color;
};
"색상" 숨기기(일부 개인 멤버 변수와 유사함):
function Box(col)
{
var color = col;
this.getColor = function()
{
return color;
};
}
사용방법:
var blueBox = new Box("blue");
alert(blueBox.getColor()); // will alert blue
var greenBox = new Box("green");
alert(greenBox.getColor()); // will alert green
자바스크립트의 OOP와 유사한 동작에 가끔 사용하는 템플릿입니다.보시는 바와 같이 폐쇄를 사용하여 프라이빗(스태틱 및 인스턴스 모두) 멤버를 시뮬레이트할 수 있습니다. what?new MyClass()
은 에 입니다.this
및 の の object object object 。prototype
'''는 '''는'''는 '''는'''입니다
var MyClass = (function () {
// private static
var nextId = 1;
// constructor
var cls = function () {
// private
var id = nextId++;
var name = 'Unknown';
// public (this instance only)
this.get_id = function () { return id; };
this.get_name = function () { return name; };
this.set_name = function (value) {
if (typeof value != 'string')
throw 'Name must be a string';
if (value.length < 2 || value.length > 20)
throw 'Name must be 2-20 characters long.';
name = value;
};
};
// public static
cls.get_nextId = function () {
return nextId;
};
// public (shared across instances)
cls.prototype = {
announce: function () {
alert('Hi there! My id is ' + this.get_id() + ' and my name is "' + this.get_name() + '"!\r\n' +
'The next fellow\'s id will be ' + MyClass.get_nextId() + '!');
}
};
return cls;
})();
이 패턴을 사용한 상속에 대한 질문을 받았습니다.다음은 예를 제시하겠습니다.
// It's a good idea to have a utility class to wire up inheritance.
function inherit(cls, superCls) {
// We use an intermediary empty constructor to create an
// inheritance chain, because using the super class' constructor
// might have side effects.
var construct = function () {};
construct.prototype = superCls.prototype;
cls.prototype = new construct;
cls.prototype.constructor = cls;
cls.super = superCls;
}
var MyChildClass = (function () {
// constructor
var cls = function (surName) {
// Call super constructor on this instance (any arguments
// to the constructor would go after "this" in call(…)).
this.constructor.super.call(this);
// Shadowing instance properties is a little bit less
// intuitive, but can be done:
var getName = this.get_name;
// public (this instance only)
this.get_name = function () {
return getName.call(this) + ' ' + surName;
};
};
inherit(cls, MyClass); // <-- important!
return cls;
})();
그리고 모든 것을 사용하는 예:
var bob = new MyClass();
bob.set_name('Bob');
bob.announce(); // id is 1, name shows as "Bob"
var john = new MyChildClass('Doe');
john.set_name('John');
john.announce(); // id is 2, name shows as "John Doe"
alert(john instanceof MyClass); // true
는 서로 (클래스는 합니다).MyClass
, . . . . . . . .announce
것을 합니다.get_name
」 「 」
한 가지 주의할 점은 인스턴스 속성을 섀도해야 한다는 것입니다. 수 .inherit
는 모든 속성을 ).hasOwnProperty
)는이며 자동으로 ( )을 추가합니다.super_<method name>
'이렇게 하다'라고 부를 수 요.this.super_get_name()
하여 '로 call
.
시제품 하고 싶은 는, 전화하면 .this.constructor.super.prototype.methodName
여러분 대부분은 http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)이 아닌 getters와 setters의 예를 들고 있는 것 같습니다.
lunched-dan이 더 가까웠지만 jsFiddle에서는 이 예가 작동하지 않았습니다.
이 예에서는 개체를 생성하는 동안만 실행되는 개인 생성자 함수를 만듭니다.
var color = 'black';
function Box()
{
// private property
var color = '';
// private constructor
var __construct = function() {
alert("Object Created.");
color = 'green';
}()
// getter
this.getColor = function() {
return color;
}
// setter
this.setColor = function(data) {
color = data;
}
}
var b = new Box();
alert(b.getColor()); // should be green
b.setColor('orange');
alert(b.getColor()); // should be orange
alert(color); // should be black
공용 속성을 할당하려는 경우 생성자를 다음과 같이 정의할 수 있습니다.
var color = 'black';
function Box()
{
// public property
this.color = '';
// private constructor
var __construct = function(that) {
alert("Object Created.");
that.color = 'green';
}(this)
// getter
this.getColor = function() {
return this.color;
}
// setter
this.setColor = function(color) {
this.color = color;
}
}
var b = new Box();
alert(b.getColor()); // should be green
b.setColor('orange');
alert(b.getColor()); // should be orange
alert(color); // should be black
그럼 '시공자' 소유물이 무슨 의미가 있을까요?그게 어디에 도움이 될 수 있을지 모르겠나?
컨스트럭터 속성의 포인트는 JavaScript에 클래스가 있는 것처럼 가장할 수 있는 방법을 제공하는 것입니다.유용하게 사용할 수 없는 작업 중 하나는 객체가 생성된 후 객체의 생성자를 변경하는 것입니다.복잡해요.
저는 몇 년 전에 꽤 포괄적인 기사를 썼습니다.http://joost.zeekat.nl/constructors-considered-mildly-confusing.html
예: http://jsfiddle.net/FZ5nC/
다음 템플릿을 사용해 보십시오.
<script>
//============================================================
// Register Namespace
//------------------------------------------------------------
var Name = Name||{};
Name.Space = Name.Space||{};
//============================================================
// Constructor - MUST BE AT TOP OF FILE
//------------------------------------------------------------
Name.Space.ClassName = function Name_Space_ClassName(){}
//============================================================
// Member Functions & Variables
//------------------------------------------------------------
Name.Space.ClassName.prototype = {
v1: null
,v2: null
,f1: function Name_Space_ClassName_f1(){}
}
//============================================================
// Static Variables
//------------------------------------------------------------
Name.Space.ClassName.staticVar = 0;
//============================================================
// Static Functions
//------------------------------------------------------------
Name.Space.ClassName.staticFunc = function Name_Space_ClassName_staticFunc(){
}
</script>
정적 클래스를 정의하는 경우 네임스페이스를 조정해야 합니다.
<script>
//============================================================
// Register Namespace
//------------------------------------------------------------
var Shape = Shape||{};
Shape.Rectangle = Shape.Rectangle||{};
// In previous example, Rectangle was defined in the constructor.
</script>
클래스 예:
<script>
//============================================================
// Register Namespace
//------------------------------------------------------------
var Shape = Shape||{};
//============================================================
// Constructor - MUST BE AT TOP OF FILE
//------------------------------------------------------------
Shape.Rectangle = function Shape_Rectangle(width, height, color){
this.Width = width;
this.Height = height;
this.Color = color;
}
//============================================================
// Member Functions & Variables
//------------------------------------------------------------
Shape.Rectangle.prototype = {
Width: null
,Height: null
,Color: null
,Draw: function Shape_Rectangle_Draw(canvasId, x, y){
var canvas = document.getElementById(canvasId);
var context = canvas.getContext("2d");
context.fillStyle = this.Color;
context.fillRect(x, y, this.Width, this.Height);
}
}
//============================================================
// Static Variables
//------------------------------------------------------------
Shape.Rectangle.Sides = 4;
//============================================================
// Static Functions
//------------------------------------------------------------
Shape.Rectangle.CreateSmallBlue = function Shape_Rectangle_CreateSmallBlue(){
return new Shape.Rectangle(5,8,'#0000ff');
}
Shape.Rectangle.CreateBigRed = function Shape_Rectangle_CreateBigRed(){
return new Shape.Rectangle(50,25,'#ff0000');
}
</script>
인스턴스화의 예:
<canvas id="painting" width="500" height="500"></canvas>
<script>
alert("A rectangle has "+Shape.Rectangle.Sides+" sides.");
var r1 = new Shape.Rectangle(16, 12, "#aa22cc");
r1.Draw("painting",0, 20);
var r2 = Shape.Rectangle.CreateSmallBlue();
r2.Draw("painting", 0, 0);
Shape.Rectangle.CreateBigRed().Draw("painting", 10, 0);
</script>
통지 기능은 A로 정의됩니다.B = 함수 A_B().이는 스크립트를 보다 쉽게 디버깅할 수 있도록 하기 위한 것입니다.Chrome의 요소 검사 패널을 열고 이 스크립트를 실행하고 디버그 역추적을 확장합니다.
<script>
//============================================================
// Register Namespace
//------------------------------------------------------------
var Fail = Fail||{};
//============================================================
// Static Functions
//------------------------------------------------------------
Fail.Test = function Fail_Test(){
A.Func.That.Does.Not.Exist();
}
Fail.Test();
</script>
다음은 컨스트럭터입니다.
function MyClass() {}
할 때
var myObj = new MyClass();
MyClass
실행되며 해당 클래스의 새 개체가 반환됩니다.
예, 클래스 선언 내에 다음과 같이 생성자를 정의할 수 있습니다.
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
나는 이 튜토리얼이 매우 유용하다고 생각했다.이 방법은 대부분의 jQuery 플러그인에서 사용됩니다.
var Class = function(methods) {
var klass = function() {
this.initialize.apply(this, arguments);
};
for (var property in methods) {
klass.prototype[property] = methods[property];
}
if (!klass.prototype.initialize) klass.prototype.initialize = function(){};
return klass;
};
지금이다,
var Person = Class({
initialize: function(name, age) {
this.name = name;
this.age = age;
},
toString: function() {
return "My name is "+this.name+" and I am "+this.age+" years old.";
}
});
var alice = new Person('Alice', 26);
alert(alice.name); //displays "Alice"
alert(alice.age); //displays "26"
alert(alice.toString()); //displays "My name is Alice and I am 26 years old" in most browsers.
//IE 8 and below display the Object's toString() instead! "[Object object]"
이 무늬는 나에게 잘 어울린다.이 패턴에서는 별도의 파일에 클래스를 만들고 "필요에 따라" 전체 앱에 로드합니다.
// Namespace
// (Creating new if not instantiated yet, otherwise, use existing and just add to it)
var myApp = myApp || {};
// "Package"
// Similar to how you would establish a package in other languages
(function() {
// "Class"
var MyClass = function(params) {
this.initialize(params);
}
// "Private Static" vars
// - Only accessible to functions in this class.
// - Doesn't get wiped out when we create a new instance.
var countInstances = 0;
var allInstances = [];
// "Private Static" functions
// - Same as above, but it's a function accessible
// only to other functions in this class.
function doSomething(){
}
// "Public Static" vars
// - Everyone has access.
// - Doesn't get wiped out when we create a new instance.
MyClass.counter = 0;
// "Public Static" functions
// - Same as above, but anyone can call this "static method".
// - Kinda like a singleton class situation.
MyClass.foobar = function(){
}
// Public properties and methods are built into the "prototype"
// - This is how each instance can become unique unto itself.
// - Establishing "p" as "local" (Static Private) variable
// simply so we don't have to keep typing "MyClass.prototype"
// for each property and function.
var p = MyClass.prototype;
// "Public" vars
p.id = null;
p.firstname = null;
p.lastname = null;
// "Private" vars
// - Only used by "this" instance.
// - There isn't "true" privacy for each
// instance so we have to fake it.
// - By tradition, we indicate "privacy"
// by prefixing it with an underscore.
// - So technically, anyone can access, but we simply
// don't tell anyone about it (e.g. in your API)
// so no one knows about it :)
p._foo = null;
p.initialize = function(params){
this.id = MyClass.counter++;
this.firstname = params.firstname;
this.lastname = params.lastname;
MyClass.counter++;
countInstances++;
allInstances.push(this);
}
p.doAlert = function(theMessage){
alert(this.firstname + " " + this.lastname + " said: " + theMessage + ". My id:" + this.id + ". Total People:" + countInstances + ". First Person:" + allInstances[0].firstname + " " + allInstances[0].lastname);
}
// Assign class to app
myApp.MyClass = MyClass;
// Close the "Package"
}());
// Usage example:
var bob = new myApp.MyClass({ firstname : "bob",
lastname : "er"
});
bob.doAlert("hello there");
아직 아무도 closure를 사용하지 않기 때문에 javascript closure를 어떻게 해야 하는지 게시하겠습니다.
var user = function(id) {
// private properties & methods goes here.
var someValue;
function doSomething(data) {
someValue = data;
};
// constructor goes here.
if (!id) return null;
// public properties & methods goes here.
return {
id: id,
method: function(params) {
doSomething(params);
}
};
};
이 솔루션에 대한 의견과 제안을 환영합니다.:)
조금 심플해졌을지도 모르지만, 2017년에 생각해 낸 것은 다음과 같습니다.
class obj {
constructor(in_shape, in_color){
this.shape = in_shape;
this.color = in_color;
}
getInfo(){
return this.shape + ' and ' + this.color;
}
setShape(in_shape){
this.shape = in_shape;
}
setColor(in_color){
this.color = in_color;
}
}
위의 클래스를 사용할 때 다음과 같은 것이 있습니다.
var newobj = new obj('square', 'blue');
//Here, we expect to see 'square and blue'
console.log(newobj.getInfo());
newobj.setColor('white');
newobj.setShape('sphere');
//Since we've set new color and shape, we expect the following: 'sphere and white'
console.log(newobj.getInfo());
보시는 바와 같이 컨스트럭터는 2개의 파라미터를 취득하고 오브젝트의 속성을 설정합니다. 수 요.setter
남아 있음을합니다.getInfo()
아, 아, 아, 아, 아, 아, 아, 네.
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★이이 a a 로 테스트했습니다.mocha
잘 되고 있어요
위의 Nick 샘플을 사용하여 Return 문을 객체 정의의 마지막 문장으로 사용하여 매개 변수 없이 객체의 생성자를 만들 수 있습니다.컨스트럭터 함수를 다음과 같이 되돌리면 오브젝트를 생성할 때마다 __constructure에서 코드가 실행됩니다.
function Box()
{
var __construct = function() {
alert("Object Created.");
this.color = 'green';
}
this.color = '';
this.getColor = function() {
return this.color;
}
__construct();
}
var b = new Box();
Typescript(Microsoft의 오픈 소스)를 사용하는 경우는, 이 기능이 유효합니다.
class BankAccount {
balance: number;
constructor(initially: number) {
this.balance = initially;
}
deposit(credit: number) {
this.balance += credit;
return this.balance;
}
}
Typescript를 사용하면 Javascript 구성으로 컴파일된 OO구조를 '가짜'로 만들 수 있습니다.대규모 프로젝트를 시작하는 경우 시간을 크게 절약할 수 있으며, 이제 막 마일스톤 1.0 버전에 도달했습니다.
http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf
위의 코드는 다음과 같이 '컴파일'됩니다.
var BankAccount = (function () {
function BankAccount(initially) {
this.balance = initially;
}
BankAccount.prototype.deposit = function (credit) {
this.balance += credit;
return this.balance;
};
return BankAccount;
})();
JavaScript에서 호출 유형은 함수의 동작을 정의합니다.
- 직접 호출
func()
- 개체에 대한 메서드 호출
obj.func()
- 생성자 호출
new func()
- 간접 호출
func.call()
또는func.apply()
함수를 호출할 때 생성자로 호출합니다.new
연산자:
function Cat(name) {
this.name = name;
}
Cat.prototype.getName = function() {
return this.name;
}
var myCat = new Cat('Sweet'); // Cat function invoked as a constructor
JavaScript의 인스턴스 또는 프로토타입 개체에는 속성이 있습니다.constructor
컨스트럭터 함수를 나타냅니다.
Cat.prototype.constructor === Cat // => true
myCat.constructor === Cat // => true
컨스트럭터 속성에 대한 이 게시물을 확인하십시오.
위에서 Blixt의 훌륭한 템플릿을 사용하다가 멀티레벨 상속(MyGrandChildClass 확장 MyChildClass 확장 MyClass)에서는 제대로 작동하지 않는다는 것을 알게 되었습니다. 즉, 첫 번째 부모의 컨스트럭터를 반복해서 호출합니다.여기 간단한 회피책이 있습니다.다단계 상속이 필요한 경우this.constructor.super.call(this, surName);
사용하다chainSuper(this).call(this, surName);
체인 함수는 다음과 같이 정의됩니다.
function chainSuper(cls) {
if (cls.__depth == undefined) cls.__depth = 1; else cls.__depth++;
var depth = cls.__depth;
var sup = cls.constructor.super;
while (depth > 1) {
if (sup.super != undefined) sup = sup.super;
depth--;
}
return sup;
}
http://www.jsoops.net/은 Js에서 op을 하기에는 꽤 좋습니다.private, protected, public 변수 및 함수를 제공하고 상속 기능도 제공하는 경우.코드 예:
var ClassA = JsOops(function (pri, pro, pub)
{// pri = private, pro = protected, pub = public
pri.className = "I am A ";
this.init = function (var1)// constructor
{
pri.className += var1;
}
pub.getData = function ()
{
return "ClassA(Top=" + pro.getClassName() + ", This=" + pri.getClassName()
+ ", ID=" + pro.getClassId() + ")";
}
pri.getClassName = function () { return pri.className; }
pro.getClassName = function () { return pri.className; }
pro.getClassId = function () { return 1; }
});
var newA = new ClassA("Class");
//***Access public function
console.log(typeof (newA.getData));
// function
console.log(newA.getData());
// ClassA(Top=I am A Class, This=I am A Class, ID=1)
//***You can not access constructor, private and protected function
console.log(typeof (newA.init)); // undefined
console.log(typeof (newA.className)); // undefined
console.log(typeof (newA.pro)); // undefined
console.log(typeof (newA.getClassName)); // undefined
ds.oop은 javascript에서 컨스트럭터와의 클래스를 선언하는 좋은 방법입니다.가능한 모든 상속 유형(c#조차 지원하지 않는1가지 유형 포함) 및 인터페이스도 지원합니다.
var Color = ds.make.class({
type: 'Color',
constructor: function (r,g,b) {
this.r = r; /* now r,g, and b are available to */
this.g = g; /* other methods in the Color class */
this.b = b;
}
});
var red = new Color(255,0,0); // using the new keyword to instantiate the class
여기서 자바 스크립트의 한 가지 포인트는 클래스리스 언어이지만 자바 스크립트의 함수를 사용함으로써 달성할 수 있습니다.이를 실현하기 위한 가장 일반적인 방법은 자바 스크립트로 함수를 만들고 새로운 키워드를 사용하여 객체를 만들고 이 키워드를 사용하여 속성 및 메서드를 정의해야 합니다.다음은 예시입니다.
// Function constructor
var calculator=function(num1 ,num2){
this.name="This is function constructor";
this.mulFunc=function(){
return num1*num2
};
};
var objCal=new calculator(10,10);// This is a constructor in java script
alert(objCal.mulFunc());// method call
alert(objCal.name);// property call
//Constructors With Prototypes
var calculator=function(){
this.name="Constructors With Prototypes";
};
calculator.prototype.mulFunc=function(num1 ,num2){
return num1*num2;
};
var objCal=new calculator();// This is a constructor in java script
alert(objCal.mulFunc(10,10));// method call
alert(objCal.name); // property call
대부분의 경우 필요한 속성을 선언해야 이 정보를 전달하는 메서드를 호출할 수 있습니다.속성을 처음 설정할 필요가 없는 경우 개체 내의 메서드를 호출할 수 있습니다.아마 가장 예쁜 방법은 아닐지 몰라도 이것은 여전히 효과가 있다.
var objectA = {
color: '';
callColor : function(){
console.log(this.color);
}
this.callColor();
}
var newObject = new objectA();
언급URL : https://stackoverflow.com/questions/1114024/constructors-in-javascript-objects
'programing' 카테고리의 다른 글
sql에서 join을 사용하여 like를 사용하는 방법 (0) | 2022.11.26 |
---|---|
PHP DOMhtml5 태그 오류/경고 (0) | 2022.11.07 |
PHP를 사용하여 암호를 암호화하고 해독하는 가장 좋은 방법? (0) | 2022.11.07 |
MySQL의 FOR UPDATE 잠금을 사용할 때 정확히 잠긴 것은 무엇입니까? (0) | 2022.11.07 |
자바 수식어의 적절한 순서(추상, 최종, 공개, 정적 등)는 무엇입니까? (0) | 2022.11.07 |