原型
共有属性提取出来放到 prototype 中:
// Person.prototype – 原型
// Person.prototype = {} – 祖先
Car.prototype = {
height: 1400,
lang: 5000,
name: 'bm',
}
function Car() {
}
var car = new Car();
例1.
Person.prototype.name = 'sunny';
function Person() {
}
var person = new Person();
Person.prototype.name = 'cherry';
// person.name => cherry
例2.
Person.prototype.name = 'sunny';
function Person() {
}
var person = new Person();
// Person.prototype.name = 'cherry';
Person.prototype = {
name: 'cherry'
}
// person.name => sunny
例3.
Person.prototype.name = 'sunny';
function Person() {
}
Person.prototype = {
name: 'cherry'
}
var person = new Person();
// person.name => cherry
原型链
Grand.prototype.lastName = "Deng";
function Grand() {
}
var grand = new Grand();
Father.prototype = grand;
function Father() {
this.name = 'ming'
}
var father = new Father();
Son.prototype = father;
function Son() {
this.name = 'smoke'
}
var son = new Son();
// son.lastName // Deng
Person.prototype = {
name: 'a',
sayName: function () {
console.log(this.name);
}
}
function Person() {
}
var person = new Person();
// person.sayName // f (){console.log(this.name);}
// person.sayName() // a
Person.prototype = {
name: 'a',
sayName: function () {
console.log(this.name);
}
}
function Person() {
this.name = "b";
}
var person = new Person();
// person.sayName() // b
//相同
var obj = {}; == var obj = new Object();
- Math.ceil()执行向上舍入,即它总是将数值向上舍入为最接近的整数;
- Math.floor()执行向下舍入,即它总是将数值向下舍入为最接近的整数;
- Math.round()执行标准舍入,即它总是将数值四舍五入为最接近的整数(这也是我们在数学课上学到的舍入规则)。
取1~100之间的随机数
for (var i = 0; i < 10; i++) {
var num = Math.floor(Math.random() * 100);
console.log(num);
}
**call/apply **
call和apply方法区别:改变this指向,传参列表不同;
call 需要把实参按照形参的个数传进去;
apply 需要传一个arguments(数组);
例1:
// call 方法 改变了this的指向;
function Person(name, age) {
this.name = name;
this.age = age;
}
var person = new Person('deng', 20);
var obj = {
}
Person.call(obj, 'chen', 30);
//obj
// {
// age: 30
// name: "chen"
// }
例2:
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Student(name, age, sex, tel, grade) {
Person.call(this, name, age, sex);
this.tel = tel;
this.grade = grade;
}
var student = new Student('sunny', 123, 'male', 139, 2017);
apply
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Student(name, age, sex, tel, grade) {
//Person.call(this, name, age, sex);
Person.apply(this, [name, age, sex]);
this.tel = tel;
this.grade = grade;
}
var student = new Student('sunny', 123, 'male', 139, 2017);