>  기사  >  웹 프론트엔드  >  JavaScript 세련된 생성자 생성자 및 생성자 속성 상세 설명_Javascript 기술

JavaScript 세련된 생성자 생성자 및 생성자 속성 상세 설명_Javascript 기술

WBOY
WBOY원래의
2016-05-16 15:33:391270검색

객체를 생성하는 것 외에도 생성자는 또 다른 유용한 작업을 수행합니다. 즉, 생성된 새 객체에 대한 프로토타입 객체를 자동으로 설정합니다. 프로토타입 객체는 ConstructorFunction.prototype 속성에 저장됩니다.

예를 들어 이전 예제를 다시 작성하고 생성자를 사용하여 "b" 및 "c" 객체를 생성하면 객체 "a"가 "Foo.prototype" 역할을 합니다.

// 构造函数
function Foo(y) {
 // 构造函数将会以特定模式创建对象:被创建的对象都会有"y"属性
 this.y = y;
}
// "Foo.prototype"存放了新建对象的原型引用
// 所以我们可以将之用于定义继承和共享属性或方法
// 所以,和上例一样,我们有了如下代码:
// 继承属性"x"
Foo.prototype.x = ;
// 继承方法"calculate"
Foo.prototype.calculate = function (z) {
 return this.x + this.y + z;
};
// 使用foo模式创建 "b" and "c"
var b = new Foo();
var c = new Foo();
// 调用继承的方法
b.calculate(); // 
c.calculate(); // 
// 让我们看看是否使用了预期的属性
console.log(
 b.__proto__ === Foo.prototype, // true
 c.__proto__ === Foo.prototype, // true
 // "Foo.prototype"自动创建了一个特殊的属性"constructor"
 // 指向a的构造函数本身
 // 实例"b"和"c"可以通过授权找到它并用以检测自己的构造函数
 b.constructor === Foo, // true
 c.constructor === Foo, // true
 Foo.prototype.constructor === Foo // true
 b.calculate === b.__proto__.calculate, // true
 b.__proto__.calculate === Foo.prototype.calculate // true
);

위 코드는 다음과 같은 관계로 표현할 수 있습니다.

생성자와 객체의 관계

위 다이어그램에서 볼 수 있듯이 각 개체에는 프로토타입이 있습니다. 생성자 Foo에는 자체 __proto__, 즉 Function.prototype이 있으며 Function.prototype의 __proto__는 Object.prototype을 가리킵니다. , Foo.prototype은 단지 명시적인 속성, 즉 b와 c의 __proto__ 속성입니다.

이 질문에 대한 완전하고 자세한 설명은 두 부분으로 구성됩니다.

객체 지향 프로그래밍 일반 이론(OOP. 일반 이론)에서는 다양한 객체 지향 패러다임과 스타일(OOP paradigms and styistics)을 설명하고 ECMAScript와의 비교도 설명합니다.

객체 지향 프로그래밍 ECMAScript 구현(OOP. ECMAScript 구현)은 특히 ECMAScript의 객체 지향 프로그래밍에 대해 설명합니다.
이제 기본 객체 원리를 이해했으므로 ECMAScript의 프로그램 실행 환경(런타임 프로그램 실행)을 살펴보겠습니다. 이를 일반적으로 "실행 컨텍스트 스택"(실행 컨텍스트 스택)이라고 합니다. 각 요소는 추상적으로 객체로 이해될 수 있습니다. 예, ECMAScript에서는 거의 모든 곳에서 객체를 볼 수 있다는 것을 발견했을 것입니다.

자바스크립트 생성자 속성에 대한 자세한 설명은 다음과 같습니다

객체의 생성자 속성은 객체를 생성한 함수를 반환하는 데 사용되며, 이를 우리가 흔히 생성자라고 부릅니다.

JavaScript에서는 프로토타입이 있는 모든 객체가 자동으로 생성자 속성을 얻습니다. 인수, 열거자, 오류, 전역, 수학, RegExp, 정규 표현식 등과 같은 일부 특수 객체를 제외하고 다른 모든 JavaScript 내장 객체에는 생성자 속성이 있습니다. 예: 배열, 부울, 날짜, 함수, 숫자, 개체, 문자열 등 모든 주요 브라우저는 이 속성을 지원합니다.

문법

객체 생성자

반환값

객체의 생성자 속성은 객체를 생성한 함수에 대한 참조를 반환합니다.

예 및 지침

다음 코드의 [네이티브 코드]는 이것이 JavaScript의 기본 내부 코드 구현임을 나타내며 코드 세부 정보를 표시할 수 없습니다.

// 字符串:String()
var str = "张三";
document.writeln(str.constructor); // function String() { [native code] }
document.writeln(str.constructor === String); // true
// 数组:Array()
var arr = [1, 2, 3];
document.writeln(arr.constructor); // function Array() { [native code] }
document.writeln(arr.constructor === Array); // true
// 数字:Number()
var num = 5;
document.writeln(num.constructor); // function Number() { [native code] }
document.writeln(num.constructor === Number); // true
// 自定义对象:Person()
function Person(){
  this.name = "CodePlayer";
}
var p = new Person();
document.writeln(p.constructor); // function Person(){ this.name = "CodePlayer"; }
document.writeln(p.constructor === Person); // true
// JSON对象:Object()
var o = { "name" : "张三"};
document.writeln(o.constructor); // function Object() { [native code] }
document.writeln(o.constructor === Object); // true
// 自定义函数:Function()
function foo(){
  alert("CodePlayer");
}
document.writeln(foo.constructor); // function Function() { [native code] }
document.writeln(foo.constructor === Function); // true
// 函数的原型:bar()
function bar(){
  alert("CodePlayer");
}
document.writeln(bar.prototype.constructor); // function bar(){ alert("CodePlayer"); }
document.writeln(bar.prototype.constructor === bar); // true
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.