javascript之面向对象

建立对象

一、姿式一函数

var person = new object();
person.name = 'jack'
person.age = 18;

person.sayName = function(){
    console.log(this.name);

二、姿式二(简单方便,推荐使用)this

var person = {
    name: 'jack',
    age: 18,
    sayName: function(){
        console.log(this.name);
    }
}

构造函数

function Person(name, age){
    this.name = name,
    this.age = age,
    this.sayName = function(){
        console.log(this.name);
    }
}

var p1 = new Person('jack', 18);
p1.sayName(); // jack

构造函数和实例对象的关系

在每个实例对象中同时有一个constructor属性,该属性指向建立该实例的构造函数prototype

function Person(name, age){
    this.name = name,
    this.age = age,
    this.sayName = function(){
        console.log('i am ' + this.name);
    }
};
var p1 = new Person('alex', 18);
var p2 = new Person('jason', 17);
console.log(p1.constructor === Person); // true
console.log(p1.constructor === p2.constructor); //true

检测对象类型,使用instanceof更加靠谱指针

console.log(p1 instanceof Person); //true
console.log(p2 instanceof Person); //true

对于每个实例来讲,sayName都是如出一辙的内容每一次生成一个实例,都必须为重复的内容,多占用一些内存,若是实例对象不少,会形成极大的内存浪费code

var fns = {
    sayName: function(){
        console.log("i am" + this.name);
    }
}

function Person(name, age){
    this.name = name,
    this.age = age,
    this.sayName = fns.sayName
}

var p1 = new Person('alex', 18);
p1.sayName();

上述方法解决了内存浪费的问题,可是看起来不够优雅,终极解决方法prototype对象

原型

JavaScript 规定,每个构造函数都有一个 prototype 属性,指向另外一个对象。ip

function F(){};
console.log(F.prototype) // Object

构造函数的 prototype 对象默认都有一个 constructor 属性,指向 prototype 对象所在函数。内存

console.log(F.prototype.constructor === F) // => true

经过构造函数获得的实例对象内部会包含一个指向构造函数的 prototype 对象的指针 proto原型

var instance = new F()
console.log(instance.__proto__ === F.prototype) // => true

这也就意味着,咱们能够把全部对象实例须要共享的属性和方法直接定义在 prototype 对象上。io

function Person(name, age){
    this.name = name
    this.age = age
}
Person.prototype.type = 'human';
Person.prototype.sayName = function(){
    console.log(this.name);
}
var p1 = new Person('alex', 18);
var p2 = new Person('jack', 18);
console.log(p1.sayName === p2.sayName); //true

构造函数、实例、原型三者之间的关系

image

注意:

"contructor"并不表示(对象)被(它)构造

p1.contructor只是经过默认的[[Prototype]]委托指向Person和“构造”毫无关系。Person.prototype的。contructor属性只是Person函数声明时的默认属性

function Person(name, age){
    this.name = name,
    this.age = age,
    this.sayName = function(){
        console.log('i am ' + this.name);
    }
};
function Test(){
    this.name = 'test';
}
Person.prototype = {
    constructor: Test
}
var p1 = new Person('alex', 18);
console.log(p1.constructor === Person) // false
console.log(Person.prototype.constructor.name) // Test

更优雅的写法

function Person(name, age){
    this.name = name,
    this.age = age
    
}

Person.Prototype = {
    contructor: Person,
    // => 手动将 constructor 指向正确的构造函数 防止原型对象丢失
    type: 'human',
    sayName: function(){
        console.log("I am " + this.name);
    }
}
相关文章
相关标签/搜索