JS 面向对象

 

字面量创建对象

let stu={
    name:'li',
    age:13,
    f:function() {
        console.log('游泳');
    }
}

//取数据
console.log(stu.name) 
console.log(stu['age'])
stu.f()

 

构造函数创建对象

function Person() {
    this.name='tom',
    this.f=function () {
        console.log('hi')
    }
}

let o=new Person()
o.f()

 

Object创建对象

//
let o=new Object()

//添加
o.name='tom'
o.f=function () {
    console.log('hi')
}

//调用
console.log(o.name)
o.f()

 

原型对象

 js通过原型来实现继承。

每一个对象都含有原型的引用,当查找属性时,若对象本身不具有该属性,则会查找原型上是否有该属性。

字面量和原型

const stu1={name:'li'}
const stu2={name:'han',age:18}

Object.setPrototypeOf(stu1,stu2)

console.log(stu1.name)
console.log(stu1.age)

构造器和原型

每一个函数都有内置的原型对象

function  TestFun() {
   
}
TestFun.prototype.word='hi'

testfun1=new TestFun()
testfun2=new TestFun()

//所有通过TestFun函数创建的对象都能读取该函数的属性
console.log(testfun1.word)
console.log(testfun2.word)

优先使用函数内的方法和属性,如果没有再去原型里找

function  TestFun() {
   this.word=1
   this.wordAdd=function() {
      return this.word+1
   }
}
TestFun.prototype.wordAdd=function(){
   return this.word*10
}

testfun1=new TestFun()
console.log(testfun1.wordAdd())

对象和函数原型之间的引用关系是在对象创建是建立的,

所以在创建后如果使用字面量方式重写了原型里的数据,那么之前创建的对象仍然使用的是老的原型引用

function TestFun() {
   this.word = 'a'
}
TestFun.prototype.wordAdd = function () {
   return this.word + 'hi'
}

testfun1 = new TestFun()

//通过字面量重写wordadd方法
TestFun.prototype = {
   wordAdd: function () {
      return this.word + 'hello'
   }
}

testfun2 = new TestFun()
console.log(testfun1.wordAdd())
console.log(testfun2.wordAdd())

结果:

ahi
ahello
 

 constructor

每一个函数的原型对象都具有一个constructor属性,该属性指向函数本身

function TestFun() {
   this.word = 'a'
}
testfun2 = new TestFun()
console.log(testfun2.constructor===TestFun) //true

还可以用对象实例的constructor属性再创建一个新对象

function TestFun() {
   this.word = 'a'
}
TestFun.
testfun1 = new TestFun()
//testfun1.word='b'
console.log(testfun1.word) 
//新创建的对象只能说明是从TestFun函数来的,对象是空对象,包括原有的原型也没了
testfun2=testfun1.constructor()

 

实现继承

 把实例化赋给需要被继承函数的使用原型

function TestFun() {
   this.word='a'
}

function TestFun2() {
   
}

TestFun2.prototype=new TestFun()
test2Fun =new TestFun2()
console.log(test2Fun.word)  //a

 

posted @ 2017-07-26 20:33  富坚老贼  阅读(112)  评论(0编辑  收藏  举报