面向对象

Posted 欢如平生

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面向对象相关的知识,希望对你有一定的参考价值。

1.封装

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>封装1</title>
</head>
<body>

</body>
<script>
  // 1.普通的对象
  var cat = {
    name: jane,
    color: yellow
  }
  console.log(cat)
  // 2.函数生成
  function Cat (name, color) {
    return {
      name: name,
      color: color
    }
  }
  var cat1 = Cat(one, green)
  var cat2 = Cat(two, yellow)
  console.log(cat1,cat2)
  // 3.构造函数
  function Cat2 (name, color) {
    this.name = name
    this.color = color
  }
  Cat2.prototype.type="猫科动物"
  Cat2.prototype.eat = function() {console.log(吃老鼠)}
  var cat3 =new Cat2(three, green)
  var cat4 =new Cat2(four, yellow)
  console.log(cat3,cat4)
  console.log(cat3.constructor)
  console.log(cat3.eat) // 吃老鼠

  // 4.Prototype模式的验证方法

  // 4.1 isPrototypeOf() 判断某个实例对象个某个实例之间的关系
  alert(Cat2.prototype.isPrototypeOf(cat3))

  // 4.2 hasOwnProperty 判断某个属性是本地属性还是继承自prototype

  alert(cat3.hasOwnProperty("name"))
  alert(cat3.hasOwnProperty("eat"))

  // 4.3 in 判断某个实例是否含有某个属性,不管是不是本地属性,in也可以遍历某个对象的所有属性
  alert("name" in cat3)
  for(var prop in cat) {
    console.log(prop)
  }
</script>
</html>

2.继承

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>继承</title>
</head>
<body>

</body>
<script>
  function Animal() {
    this.species = "动物"
  }
  function Cat (name, color) {
    this.name = name
    this.color = color
  }

  console.log(Animal())

  // 1. call/apply,将父对象的构造函数绑定在子对象上,直接改变this的指向
  function Cat(name, color) {
    Animal.apply(this, arguments)
    this.name = name
    this.color = color
  }

  var cat1 = new Cat(大黄, 蓝色)
  console.log(cat1.species)

  // 2. prototype
  Cat.prototype = new Animal()
  Cat.prototype.constructor = Cat
  var cat2 = new Cat(大黄, 蓝色)
  console.log(cat2.species)
  // 3. 直接继承prototype
  function Animal1 () {}
  Animal1.prototype.species = "动物"
  Cat.prototype = Animal1.prototype
  Cat.prototype.constructor = Cat

  var cat3 = new Cat(大黄, 蓝色)

  console.log(cat3.species)
  console.log(Animal1.prototype.constructor)

  // 4. 空对象继承
 function extend(Child, Parent) {
  var F = function(){};
  F.prototype = Parent.prototype;
  Child.prototype = new F();
  Child.prototype.constructor = Child;
  Child.uber = Parent.prototype;
 }
// 5.拷贝继承
  function extend2 (Child, Partent) {
    var p = Partent.prototype
    var q = Child.prototype
    for (var prop in p) {
      q[prop] = p[prop]
    }
    q.uber = p
  }
</script>
</html>

 

以上是关于面向对象的主要内容,如果未能解决你的问题,请参考以下文章

面向面试编程代码片段之GC

PHP面向对象之选择工厂和更新工厂

Java中面向对象的三大特性之封装

python之路之前没搞明白4面向对象(封装)

Scala的面向对象与函数编程

Python面向对象学习之八,装饰器