Heim > Web-Frontend > js-Tutorial > Hauptteil

js 编写规范_基础知识

WBOY
Freigeben: 2016-05-16 18:33:37
Original
1018 Leute haben es durchsucht

在一个项目中大量使用js,工程项目与网站开发有一些不一样,在我接触的工程项目中普遍使用js 不够多,大部分客户端可做事,交给了服务端,而且在使用js时不够规范,很容易造成代码难以阅读、内存泄漏问题,不注意js 输写方式。而在网站开发中(尤其一些大网站,js输出的非常漂亮、完美无论使用jquery,还是prototype 框架,还是不用框架,都有自己良好一套东东可用)
js输写最好还是可以面向对象方式 用类方向进行包装 js输写两种方式 闭包 原型
闭包:(借用的一个例子)

复制代码 代码如下:

function Person(firstName, lastName, age)
{
//私有变量:
var _firstName = firstName;
var _lastName = lastName;
//公共变量:
this.age = age;
//方法:
this.getName = function()
{
return(firstName + " " + lastName);
};
this.SayHello = function()
{
alert("Hello, I'm " + firstName + " " + lastName);
};
};
var BillGates = new Person("Bill", "Gates", 53);

原型:(借用的一个例子)
复制代码 代码如下:

  //定义构造函数
function Person(name)
{
this.name = name; //在构造函数中定义成员
};
//方法定义到构造函数的prototype上
Person.prototype.SayHello = function()
{
alert("Hello, I'm " + this.name);
};
//子类构造函数
function Employee(name, salary)
{
Person.call(this, name); //调用上层构造函数
this.salary = salary; //扩展的成员
};
//子类构造函数首先需要用上层构造函数来建立prototype对象,实现继承的概念
Employee.prototype = new Person() //只需要其prototype的方法,此对象的成员没有任何意义!
//子类方法也定义到构造函数之上
Employee.prototype.ShowMeTheMoney = function()
{
alert(this.name + " $" + this.salary);
};
var BillGates = new Person("Bill Gates");
BillGates.SayHello();
var SteveJobs = new Employee("Steve Jobs", 1234);
SteveJobs.SayHello();

这两种方法各有优缺点,第一种看起来更像一个类 每个对象设置一份方法有很大浪费,而且资源回收不利,第二种方法,看起来不是很漂亮,可性能很好(不过如果你使用prototype框架,就可以完美解决结构与性能问题了。)

实际在使用jquery 还是prototype问题上,我的一点点体会是 jquery使用闭包方式,而prototype当然原型,jquery更加适合对单个对象操作,而prototype更适合做一些客户端控件。实际我更喜欢在项目中使用jquery 而网站上更关注prototype
Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!