万字长文深度剖析面向对象的javascript

前端开发 作者: 2024-08-21 11:30:01
简介 本将会深入讲解面向对象在javascript中的应用,并详细介绍三种对象的生成方式:构造函数,原型链,类。 什么是对象 虽然说程序员不缺对象,随时随地都可以new一个出来,但是在程序的世界中,对

简介

什么是对象

  • 构造函数(constructor)
  • 原型链(prototype)
  • 类(class) ---ES6提供

构造函数

var Book  = function () {
    this.name = 'www.flydean.com';
}
var Book  = function () {
    this.name = 'www.flydean.com';
}

var b1 = new Book();
console.log(b1.name);
www.flydean.com
var Book  = function () {
    this.name = 'www.flydean.com';
}

var b2 = Book();
console.log(name);
console.log(b2.name);
TypeError: Cannot read property 'name' of undefined
function Person(firstname,lastname){

    if(!(this instanceof Person)){
        return new Person(firstname,lastname);
    }
    this.firstname= firstname;
    this.firstname = lastname;
}

console.log(Person("jack","ma").firstname);
console.log((new Person("jack","ma")).firstname);
  1. 创建一个空对象,作为将要返回的对象实例
  2. 将这个空对象的原型,指向构造函数的prototype属性
  3. 将这个空对象赋值给函数内部的this关键字
  4. 开始执行构造函数内部的代码
var Book  = function () {
    this.name = 'www.flydean.com';
    return {author:'flydean'};
}

console.log((new Book()).author);
function f(){
    if(! new.target){
        throw new Error('请使用new命令!');
    }
}
f();
var book2 = {
    name : '三毛流浪记',author : '三毛',getName : function () {
        console.log('book name is:' + this.name);
    }
}
var book3 = Object.create(book2);
console.log(book3.name);
book3.getName();

prototype对象

function Book(){
    this.name ='www.flydean.com';
    this.getName =function (){
        console.log('flydean');
    }
}

var book1 = new Book();
var book2  = new Book();

console.log(book1.getName  === book2.getName);
function Book(name){
    this.name = name;
}

Book.prototype.author ='flydean';
var book1 = new Book();
var book2 = new Book();
console.log(book1.author);
console.log(book2.author);
console.log(Object.getPrototypeOf(Object.prototype));
//null
function Book(name){
    this.name = name;
}
var book3 =new Book();
console.log(book3.constructor);
console.log(book3.constructor === Book.prototype.constructor);
console.log(book3.hasOwnProperty(constructor));
function A(){}
var a = new A();
console.log(a instanceof A);
function B(){}
A.prototype = B.prototype;
console.log(a instanceof A);
//不要这样写
A.prototype  ={
    method1:function (){}
}

//比较好的写法
A.prototype  ={
    constructor:A,method1:function (){}
}
//更好的写法
A.prototype.method1 = function (){}

Object的prototype操作


//空对象的prototype是Object.prototype
console.log(Object.getPrototypeOf({}) === Object.prototype);

//function的prototype是Function.prototype
function f(){}
console.log(Object.getPrototypeOf(f)  === Function.prototype);

function F(){this.name ='flydean'}
var f1 =new F();
console.log(Object.getPrototypeOf(f1) === F.prototype);

var f2 = new f();
console.log(Object.getPrototypeOf(f2) === f.prototype);

var a = {name: 'flydean'};
var b = Object.setPrototypeOf({},a);
console.log(b.name);
var a = {name: 'flydean'};
var b = Object.setPrototypeOf({},a);
console.log(a.isPrototypeOf(b));
var a = {name: 'flydean'};

var c ={};
c.__proto__ = a;
console.log(Object.getPrototypeOf(c));
  • obj.proto
  • obj.constructor.prototype
  • Object.getPrototypeOf(obj)

this对象

var book = {
    name :'flydean',getName : function (){
        return '书名:'+ this.name;
    }
}

console.log(book.getName());
//书名:flydean
var book = {
    name :'flydean',getName : function (){
        return '书名:'+ this.name;
    }
}

var car ={
    name :'car'
}

car.getName = book.getName;
console.log(car.getName());
//书名:car
var book1 = {
    name :'flydean',book2: {
        getName : function (){
            return '书名:'+ this.name;
        }
    }
}
console.log(book1.book2.getName());
//书名:undefined
var book3 = {
    name :'flydean',book4: function(){
        console.log('book4');
        var getName = function (){
            console.log(this); //Window
        }();
    }
}
book3.book4();
var book5 ={
    name : 'flydean',author : ['max','jacken'],f: function (){
        this.author.forEach(function (item) {
            console.log(this.name+' '+item);
        })
    }
}
book5.f();
//undefined max
//undefined jacken
var book6 ={
    name : 'flydean',f: function (){
        var that = this;
        this.author.forEach(function (item) {
            console.log(that.name+' '+item);
        })
    }
}
book6.f();
//flydean max
//flydean jacken
var book7 ={
    name : 'flydean',f: function (){
        this.author.forEach(function (item) {
            console.log(this.name+' '+item);
        },this)
    }
}
book7.f();
//flydean max
//flydean jacken

绑定this的方法

var book = {};

var f = function () {
    return this;
}
f()  === this ; //true
f.call(book) === book; //true
var f = function () {
    return this;
}

console.log(f.call(100));
//[Number: 100]
func.call(thisValue,arg1,arg2,...);
var person =  {};

person.hasOwnProperty('getName');//false

//覆盖person的getName方法
person.getName  = function(){
    return true;
}

person.hasOwnProperty('getName');//true
Object.prototype.hasOwnProperty.call(person,'getName');//false
func.apply(thisValue,[arg1,...])
var d = new Date();

console.log(d.getTime()); //1600755862787

var getTime= d.getTime;
console.log(getTime());//TypeError: this is not a Date object.
var d = new Date();

console.log(d.getTime()); //1600755862787

var getTime2= d.getTime.bind(d);
console.log(getTime2());
var add = function(x,y){
    return x +this.m +  y + this.n;
}
var addObj ={
    m: 10,n: 10
}

var newAdd = add.bind(addObj,2);
console.log(newAdd(3));//25

继承

function Person (){
    this.name = 'person';
}

function Boy(){
    Person.call(this);
    this.title = 'boy';
}

Boy.prototype= Object.create(Person.prototype);
Boy.prototype.constructor=Boy;
Boy.prototype.getTitle=function (){console.log(this.title)};

var b =new Boy();
b.getTitle();
console.log(b);
~~

调用父类的构造函数是初始化实例对象的属性。子类的原型指向父类的原型是为了基础父类的原型对象的属性。

另外一种写法是Boy.prototype等于一个父类实例:

~~~js
Boy.prototype = new Person();
function Person1 (){
    this.name = 'person';
}
function Person2 (){
    this.sex = '男';
}

function Boy(){
    Person1.call(this);
    Person2.call(this);
    this.title = 'boy';
}

//继承Person1
Boy.prototype= Object.create(Person1.prototype);
//继承链加上Person2
Object.assign(Boy.prototype,Person2.prototype);

Boy.prototype.constructor=Boy;
Boy.prototype.getTitle=function (){console.log(this.title)};

var b =new Boy();
b.getTitle();
console.log(b);
//Boy { name: 'person',sex: '男',title: 'boy' }

class

class Person {
    constructor(name,sex) {
        this.name=name;
        this.sex =sex;
    }

    toString(){
        return this.name + ' '+ this.sex;
    }
}
Person.prototype = {
       constructor(name,sex) {
        this.name=name;
        this.sex =sex;
    }

    toString(){
        return this.name + ' '+ this.sex;
    } 
}
let methodName = 'getName';

class Person {
    constructor(name,sex) {
        this.name=name;
        this.sex =sex;
    }

    toString(){
        return this.name + ' '+ this.sex;
    }

    [methodName](){
        return this.name;
    }
}
class Person {
    constructor(name,sex) {
        this.name=name;
        this.sex =sex;
    }

    static getSex(){
        return '男';
    }
}

console.log(Person.getSex()); //男

let  p  = new Person();
console.log(p.getSex());//TypeError: p.getSex is not a function

class Person {
    constructor(name,sex) {
        this.name=name;
        this.sex =sex;
    }
}
Person.address ='address';
console.log(Person.address);
class Boy extends Person{
    constructor(name,sex,address) {
        super(name,sex); //调用父类的构造函数
        this.address =address;
    }

    toString() {
        return super.toString();//调用父类的方法
    }
}
class Boy extends Person{
    constructor(name,sex); //调用父类的构造函数
        console.log(super.name);  //undefined
        console.log(this.name);  //hanmeimei
        this.address =address;
    }

    toString() {
        return super.toString();//调用父类的方法
    }

    getName(){
        console.log(super.name);  //undefined
        console.log(this.name);    //hanmeimei
    }
}

var b =new Boy('hanmeimei','女','北京');
b.getName();

总结

原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_66065.html