文章目录
一、构造函数
function Start() {
this.name = name;
this.age = age;
this.sing = function(){
conslose.log('我会唱歌');
}
}
实例成员和静态成员
实例成员就是构造函数内部通过this添加的成员,实例成员只能通过实例化的对象来访问
静态成员在构造函数本身上添加的成员, 静态成员只能通过构造函数来访问。
<script>
function Start() {
this.name = name;
this.age = age;
this.sing = function () {
console.log('唱歌');
}
}
// sex 就是静态成员
Start.sex = '男';
// 静态成员只能通过构造函数来访问。
console.log(Start.sex);
</script>
二、构造函数原型对象 prototype
构造函数存在浪费内存的问题。
构造函数通过原型分配的函数是所有对象所共享的。
每一个构造函数都有一个prototype属性。
prototype就是一个对象
我们可以把那些不变的方法,直接定义在prototype对象上,这样所有对象的实例就可以共享这些方法。
<script>
function Start(uname, age) {
this.uname = uname;
this.age = age;
}
Start.prototype.sing = function () {
console.log("我是谁?", this.uname);
}
var s1 = new Start('张三');
s1.sing();
</script>
一般情况下, 我们的公共属性定义到构造函数里面。 公共的方法我们放到原型对象身上。
三、对象原型 proto
对象都会有一个属性
__proto__
指向构造函数的prototype
原型对象。
实例对象的__proto__
和 构造函数的prototype
是等价的。
<script>
function Start(uname, age) {
this.uname = uname;
this.age = age;
}
Start.prototype.sing = function () {
console.log("我是谁?", this.uname);
}
var s1 = new Start('张三');
console.log(s1.__proto__ == Start.prototype); // true
</script>
方法的查找规则 :
首先看实例对象(s1)身上是否有sing方法,如果有就执行这个对象上的sing
如果没有这个方法,因为有__proto__的存在,就去构造函数原型对象prototype身上去查找sing这个方法。
四、constructor构造函数
对象原型(__proto__)
和构造函数(prototype)原型对象
里面都有一个constructor
属性,constructor
我们称为构造函数,因为它指回构造函数本身。
<script>
function Start(uname, age) {
this.uname = uname;
this.age = age;
}
Start.prototype.sing = function () {
console.log("我是谁?", this.uname);
}
var s1 = new Start('张三');
console.log(s1.__proto__); // true
console.log(Start.prototype);
</script>
constructor主要用于记录该对象引用于哪个构造函数。
五、原型链
JavaScript的成员查找机制
- 当访问一个对象的属性时, 首先查找这个对象自身有没有该属性
- 如果没有就查找它的原型。(就是__proto__指向的prototype原型对象)
- 如果还没有就查找原型对象的原型 (Object的原型对象)
- 依此类推一直找到Object为止。
原型对象this指向
- 在构造函数中,里面的this指向的是对象实例。
- 原型对象函数里面的this指向的是实例对象
扩展内置对象
<script>
Array.prototype.sum = function () {
var sum = 0;
for (var i = 0; i < this.length; i++) {
sum += this[i];
}
return sum;
}
var arr1 = [1, 2, 3, 4];
console.log(arr1.sum());
</script>
数组和字符串内置对象不能给原型对象覆盖操作
Array.prototype = {}
只能是Array.prototype.xxx = function(){}
的方式。