作业:创建对象的方式(字面量或构造函数)
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS中的对象创建</title> </head> <body> <h2>用字面量创建对象</h2> <hr> <script > let obj = 100; let obj1 = '南通税企通'; document.write(obj1,'<br>',obj,'<hr>'); let obj2 = { name:'arthur', position:'管理员', salary:19800, secret: function () { return this.salary; } }; document.write(obj2.name,'<br>'); document.write(obj2.position,'<br>'); document.write(obj2.secret(),'<hr>'); </script> <h2>用构造函数创建对象</h2> <hr> <script> function Staff(name,position,salary){ this.name = name; this.position = position; this.salary = salary; this.getName = function () { return [this.name,this.position,this.salary]; } } let staff1 = new Staff('arthur','admin',19800); let staff2 = new Staff('kitty','assistant',8800); document.write(staff1.getName(),'<br>'); document.write(staff2.getName(),'<hr>'); document.write(typeof staff1.constructor,'<br>'); document.write(staff1.constructor,'<br>'); document.write(staff1.constructor === Staff,'<br>'); document.write(staff1 instanceof Staff,'<br>'); document.write(staff1 instanceof Object,'<hr>'); document.write(this,'<br>'); Staff('baby','desktop','3800'); document.write(window.getName(),'<hr>'); staff3 = new Staff(); Staff.call(staff3,'a','a1','123'); document.write(staff3.getName(),'<br>'); Staff.apply(staff3,['b','b2',321]); document.write(staff3.getName(),'<hr>'); </script> <h2>原型模式创建对象</h2> <hr> <script > function Shop(shoes,clothes,jeans) { Shop.prototype.shoes = shoes; Shop.prototype.clothes = clothes; Shop.prototype.jeans = jeans; Shop.prototype.getInfo = function () { return this.shoes +',' +this.clothes +','+ this.jeans; } } let shop1 = new Shop('李宁','班尼路','某易斯.威登'); document.write(shop1.getInfo(),'<br>'); let shop2 = new Shop('乔丹','李维斯','某思哲'); document.write(shop1.getInfo(),'<br>'); document.write(shop2.getInfo(),'<hr>'); document.write(Shop.constructor,'<br>'); document.write(typeof Shop.prototype,'<br>'); document.write(Shop.prototype.constructor,'<hr>'); document.write(Shop.constructor === shop1.constructor.prototype.constructor); </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
总结:写完了,终于把JS中对象了解到一定程度了,所谓的一切皆对象,就说明了一切皆虚幻,存在于自己怎么理解而已!