jsÖÐʲôÊǽṹº¯Êý
ÔÚ javascript ÖУ¬½á¹¹º¯ÊýÊÇÓÃÓÚ½¨É蹤¾ßʵÀýµÄÌØÊ⺯Êý¡£ËüµÄ×÷ÓðüÀ¨£º½¨É蹤¾ß³õʼ»¯ÊôÐÔÓ¦ÓÃÐÐΪ½á¹¹º¯Êýͨ¹ý new Òªº¦×ÖŲÓã¬ÀýÈ磺const object = new constructorfunction(arg1, arg2, …)¡£
ʲôÊǽṹº¯Êý
ÔÚ JavaScript ÖУ¬½á¹¹º¯ÊýÊÇÒ»¸öÌØÊâµÄº¯Êý£¬ÓÃÓÚ½¨ÉèÒ»¸ö¹¤¾ßµÄʵÀý£¬²¢½«Æä³õʼ»¯¡£ËüÊÇÒ»¸ö¿ÉÒÔͨ¹ý new Òªº¦×ÖŲÓõĺ¯Êý¡£Ëü²î±ðÓÚͨË׺¯Êý£¬ÓÉÓÚËü»á½¨ÉèÒ»¸öй¤¾ß£¬²¢½«Æä×÷Ϊ this Òªº¦×ÖµÄÉÏÏÂÎÄ¡£
½á¹¹º¯ÊýµÄ×÷ÓÃ
½¨É蹤¾ß£º ½á¹¹º¯Êý¿ÉÒÔ½¨ÉèÌض¨ÀàÐ͵Äй¤¾ß¡£
³õʼ»¯ÊôÐÔ£º ½á¹¹º¯Êý¿ÉÒÔÔÚ¹¤¾ß½¨Éèʱ³õʼ»¯ÆäÊôÐÔ¡£
Ó¦ÓÃÐÐΪ£º ½á¹¹º¯Êý¿ÉÒÔ½ç˵¹¤¾ßµÄÐÐΪ£¬ÀýÈçÒªÁìºÍÊÂÎñ´¦Öóͷ£³ÌÐò¡£
½á¹¹º¯ÊýµÄÓï·¨
function ConstructorFunction(²ÎÊý1, ²ÎÊý2, ...) { // ³õʼ»¯¹¤¾ßµÄÊôÐÔºÍÐÐΪ }
µÇ¼ºó¸´ÖÆ
½á¹¹º¯ÊýµÄŲÓÃ
½á¹¹º¯ÊýÊÇͨ¹ý new Òªº¦×ÖŲÓõġ£ÀýÈ磺
const object = new ConstructorFunction(arg1, arg2, ...);
µÇ¼ºó¸´ÖÆ
Õâ»á½¨ÉèÒ»¸ö object ¹¤¾ß£¬ËüÊÇÒ»¸ö ConstructorFunction µÄʵÀý¡£
Àý×Ó
ÒÔÏÂÊÇÒ»¸öʾÀý½á¹¹º¯Êý£¬ÓÃÓÚ½¨ÉèÌåÏÖÈ˵Ť¾ß£º
function Person(name, age) { this.name = name; this.age = age; }
µÇ¼ºó¸´ÖÆ
Õâ¸ö½á¹¹º¯Êý½¨ÉèÁËÒ»¸ö¾ßÓÐ name ºÍ age ÊôÐÔµÄРPerson ¹¤¾ß¡£
const person1 = new Person("John", 30);
µÇ¼ºó¸´ÖÆ
Õâ»á½¨ÉèÒ»¸ö¾ßÓÐÊôÐÔ name Ϊ “John” ºÍ age Ϊ 30 µÄ person1 ¹¤¾ß¡£
ÒÔÉϾÍÊÇjsÖÐʲôÊǽṹº¯ÊýµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡