
Java开发


课程针对企业需求实时更新

企业级项目精炼 助力高薪
1.通过写出函数检测JavaScript中一个变量是一个String类型
typeof(obj) === "string"
typeof obj === "string"
obj.constructor === String
2.字符串的空格用js去除
方法一:使用replace正规匹配
去除所有空格: str = str.replace(/s*/g,"");
去除两头空格: str = str.replace(/^s*|s*$/g,"");
去除左空格: str = str.replace( /^s*/, “”);
去除右空格: str = str.replace(/(s*$)/g, "");
str为要去除空格的字符串,实例如下:
var str = " 23 23 ";
var str2 = str.replace(/s*/g,"");
console.log(str2); // 2323
方法二:使用str.trim()方法
var str = " xiao ming ";
var str2 = str.trim();
console.log(str2); //xiao ming
同理,str.trimLeft(),str.trimRight()分别用于去除字符串左右空格。
方法三:使用jquery,$.trim(str)方法
var str = " xiao ming ";
var str2 = $.trim(str)
console.log(str2); // xiao ming
A.原型链(prototype chaining)
function car(price){
this.price = price;
}
car.prototype.sayPrice = function(){
console.log("Price is "+this.price);
}
var oCar = new car("100W");
oCar.sayPrice();
function toyCar(price){
this.price = price;
}
toyCar.prototype = new car()
var oCar2 = new toyCar("10CNY");
oCar2.sayPrice();
B.call()/apply()
function useCall(a,b){
this.a = a;
this.b = b;
this.say = function(){
console.log("I'm "+this.a+" You're "+this.b);
}
}
function callThefunction (){
var args = arguments;
useCall.call(this,args[0],args[1]);
// useCall.apply(this,arguments);
}
var testCall1 = new useCall("Not YY","Not TT");
testCall1.say();
var testCall2 = new callThefunction("YY","TT");
testCall2.say();
// I'm Not YY You're Not TT
// I'm YY You're TT
C.混合方式(prototype和call()/apply()结合)
function house(size,price){
this.size = size;
this.price = price;
}
house.prototype.showArea=function (){
console.log("面积为"+this.size);
}
house.prototype.sayPrice=function (){
console.log("价钱为"+this.price);
}
function maofan(size,price){
house.call(this,size,price);
}
maofan.prototype = new house();
var newmaofan = new maofan("20Square meters ","1000CNY");
newmaofan.showArea();
D.对象冒充
function Person(name,age){
this.name = name;
this.age = age;
this.show = function(){
console.log(this.name+", "+this.age);
}
}
Person.prototype.sayHi = function(){
alert('hi');
}
function Student(name,age){
this.student = Person; //将Person类的构造函数赋值给this.student
this.student(name,age); //js中实际上是通过对象冒充来实现继承的
delete this.student; //移除对Person的引用
}
var s = new Student("小明",17);
s.show();
var p = new Person("小花",18);
p.show();
// 小明, 17
// 小花, 18
注:本文部分内容以及图片来源于网络,如网站发布的有关的信息侵犯到您的权益,请及时与我们取得联系删除
热门课程
免费试听
上课方式
开班时间
实战教学·项目驱动
网络安全
6月26日
JAVA
6月26日
前端
6月26日
Chat GPT
05月30日
24小时报名热线
177 1362 3990