1.课程目标:
1.1:原型怎么写? 1.2:prototype的特点是什么? 1.3:对象的三角恋关系是怎么样的?
形式:构造函数名.prototype= { 函数名:function() { console.log("原型的写法"); } }2.原型怎么写?
原型怎么写?
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script type="text/javascript"> /*let fns={ mySay:function() { console.log("7"); } }*/ function Person(myName, myAge) { this.name = myName; this.age = myAge; //this.say=fns.mySay; //可以简化为: /*this.say=function() { console.log("7"); }*/ } Person.prototype={ say:function() { console.log("666"); } }; let obj1 = new Person("lnj", 34); obj1.say(); let obj2 = new Person("zs", 44); obj2.say(); console.log(obj1.say === obj2.say); // true,因为都是在同一个原型里面找到的.构造方法里面没有say函数. </script> </body> </html>总结:
1.创建对象后,构造函数里面找不到就去原型里面找.
效果:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>99-JavaScript-prototype特点</title> <script> function Person(myName, myAge) { this.name = myName; this.age = myAge; this.currentType = "构造函数中的type"; this.say = function () { console.log("构造函数中的say"); } } Person.prototype = { currentType: "人", say: function () { console.log("hello world"); } } let obj1 = new Person("lnj", 34); obj1.say(); console.log(obj1.currentType); let obj2 = new Person("zs", 44); obj2.say(); console.log(obj2.currentType); </script> </head> <body> </body> </html>总结:
1.记住,是构造方法里面没有才去原型里面找的哈,比如我有钱我为什么要去借钱是吧.
效果:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>100-JavaScript-对象三角恋关系</title> <script> function Person(myName, myAge) { this.name = myName; this.age = myAge; } let obj1 = new Person("lnj", 34); //这里代表的都是指向哪里的哈. console.log(Person.prototype); console.log(Person.prototype.constructor); console.log(obj1.__proto__); </script> </head> <body> </body> </html>总结:
每个“构造函数”中都有一个默认的属性,叫做prototype,prototype属性保存着一个对象,这个对象我们称之为“原型对象”。 每个“原型对象”中都有一个默认的属性,叫做constructor , constructor指向当前原型对象对应的那个“构造函数”。 通过构造函数创建出来的对象,我们称之为“实例对象”, 每个“实例对象”中都有一个默认的属性,叫做__proto__, __proto__指向创建它的那个构造函数的“原型对象”。**
效果:
三角恋图: