1-1 对象

  1. 某一类事物的具体实例

1-2 类

  1. 对某一具体事物的抽象

1-3 构造函数

1-3-1 实例

  1. 实例: new 出来的对象

1-3-2 构造函数的缺点

  1. 同一个构造函数的多个实例之间,无法共享属性,从而造成对系统资源的浪费。
  1. /* 公有的属性或者公有的方法我们可以放在原型对象上 */
  2. function Person(name,age){
  3. this.name = name
  4. this.age = age
  5. }
  6. Person.prototype.eat = "水果"
  7. var p = new Person("li",19)
  8. var zhang = new Person("zhang",20)
  9. console.log(p);
  10. console.log(zhang);

1-3-3 构造函数

  1. 构造函数:构造一个类(对象)的函数
  2. 构造函数的特点:
  3. 1.首字母大写
  4. 2.函数内部使用this关键字,谁new(实例化)就指向谁
  5. 3.使用this关键字给对象添加属性
  6. 4.必须使用new关键字,去生成一个对象
  1. // 在 javascript 中新建一个类 使用构造函数
  2. function Student(name,age){
  3. this.name = name;
  4. this.age=age
  5. }
  6. /* this 指实例化的对象 */
  7. /* 实例 */
  8. var zheng = new Student("zcy",18)
  9. console.log(zheng);
  10. // 读取对象的属性
  11. console.log(p.name);
  12. console.log(p.age);

1-3-4 instanceof 判断一个对象是不是某个类的实例

  1. var arr = [1,2,3]
  2. console.log(arr instanceof Array); // true
  3. function Person(name,age){
  4. this.name = name
  5. this.age = age
  6. }
  7. var p = new Person("zheng",18)
  8. console.log(p instanceof Person); // true

构造函数例子

  1. <script>
  2. Array.prototype.push = function(){
  3. console.log("失效了")
  4. }
  5. var arr = [];
  6. arr.push(4);
  7. console.log(arr)
  8. /* remove(value) */
  9. Array.prototype.remove= function(val){
  10. var index = this.indexOf(val);
  11. this.splice(index,1);
  12. return this;
  13. }
  14. var arr = [5,6,7];
  15. console.log(arr.remove(6));
  16. /* sum */
  17. Array.prototype.sum = function(){
  18. var s= 0;
  19. for(var i=0;i<this.length;i++){
  20. s+=this[i];
  21. }
  22. return s;
  23. }
  24. var test = [1,2,3];
  25. console.log(test.sum())
  26. </script>

判断一个属性是自由的还是共有的

  1. console.log(p.hasOwnPropery("kill"));