自定义构造函数
- this指向的是对象本身 -- 只有new了之后才有对象
- 函数不执行,this是不存在的
function Teacher (){
this.name = "张三";
this.age = 33;
this.smoke = function (){
console.log("I am smoking");
}
}
var teach1 = new Teacher();
var teach2 = new Teacher();
function Numadd() {
this.arr = [];
for (var i = 0; i < arguments.length; i++) {
if (typeof (arguments[i]) !== "number") {
console.log("参数必须全是数字类型");
return;
}
this.arr.push(arguments[i]);
}
this.adds = function () {
this.a = 0;
for(var i = 0;i < this.arr.length;i++) {
this.a += this.arr[i];
}
return this.a;
},
this.chang = function () {
this.a = 1;
for(var i = 0;i < this.arr.length;i++) {
this.a *= this.arr[i];
}
return this.a;
}
}
var add = new Numadd(1, 2, 3,4,5);
console.log(add.adds());
console.log(add.chang());
function Car(opt) {
this.pin = opt.pin;
this.color = opt.color;
this.pai = opt.pai;
}
function Maincar(opt) {
this.name = opt.name;
this.age = opt.age;
this.inco = opt.inco;
this.print = function () {
var val = new Car(opt.sing);
console.log("我选了一辆" + val.pin + " 颜色是 " + val.color + " 排量 " + val.pai);
}
}
var main = new Maincar({
name: 'Maincar',
age: 25,
inco: 9000,
sing: {
pin: '马自达',
color: 'black',
pai: '2.0'
}
});
main.print();
- 构造函数的AO
- 其实new的时候,把原本指向window的this,转向实例化对象
function Car(color){
this.color = color
}
var car1 = new Car("red");
console.log(car1.color);
function Carx(color){
var me = {};
me.color = color;
return me;
}
var car2 = Carx("red");
console.log(car2.color);
- 当你return引用值的时候,函数,对象,数组,是会返回引用值,原始类型值不会改变。
function Car(){
this.color = "red";
}
包装类
- 原始值没有自己的方法和属性
- 内置的包装有三种
- new Number
- new String
- new Boolean
var a = 1;
console.log(a);
var b = new Number(a);
b.len = 1;
b.add = function (){};
console.log(b.len);
var a = 123;
a.len = 3;
console.log(a.len);
var a = new Number(123);
var str = "abc";
console.log(str.length);
var name = "languiji";
name += 10;
var type = typeof(name);
if(type.length === 6){
type.text = "string";
}
console.log(type.text);
var type = new String(typeof(name));
function test() {
var d = 1;
function f() {
d++;
console.log(d);
}
this.g = f;
}
var t = new test();
t.g();
t.g();
var t1 = new test();
t1.g();
var x = 1,y = z = 0;
function add(n){
return n = n + 1;
}
y = add(x);
function add(n){
return n = n + 3;
}
z = add(x);
console.log(x,y,z);
function foo1(x){
console.log(arguments);
return x;
}
foo1(1,2,3,4,5);
function foo2(x){
console.log(arguments);
return x;
}(1,2,3,4,5);
(function foo3(x) {
console.log(arguments);
return x;
})(1,2,3,4,5);
function setting(){
var pos = arguments[0];
var eit = 0;
for(var i = 0;i < pos.length;i++){
var end = pos[i].charCodeAt(0);
if(end >= 0 && end <= 255){
eit += 1;
}else {
eit += 2;
}
}
return eit;
}
console.log(setting("122侯1111王"));
var arr = [1,2,3,4,5,6];
arr.length = 3;
console.log(arr);